Next greater element problem

closed account (1vf9z8AR)
There is an input of a number N. Then there are N inputs in the next line.

Each input denotes the height of the Nth building.
Spiderman can only go to next higher building.

How many buildings can spiderman go to for each building?

for input
5
1 2 2 3 1
output
2 1 1 0 0

My logic:
Using a stack to find the next greater element during input.
Use the already found values to compute the answer.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
  #include<iostream>
#include<stack>
using namespace std;
int main()
{
    int n;
    cin>>n;
    int arr[n],nge[n];
    stack<int>s;
    for(int i=0;i<n;i++)
    {
        nge[i]=0;
        cin>>arr[i];
        if(s.empty()==true)
            s.push(i);
        else
        {
            while(arr[s.top()]<arr[i] && s.empty()==false)
            {
                nge[s.top()]=arr[i];
                s.pop();
            }
            s.push(i);
        }
    }
    while(s.empty()==false)
    {
        nge[s.top()]=0;
        s.pop();
    }
    for(int i=0;i<n;i++)
        cout<<nge[i]<<" ";
}


No output is coming.
Hello suyashsing234,

The first problem I found if line 8. "n" has to be a constant value either 10 or a variable defined as a constant. This type of array needs a constant value at compile time so the compiler will know how much memory to set aside for the array.

If you need to input a value for "n" and use it then you will have to create a dynamic array.

For what you have you are stuck with something like this:
1
2
3
4
5
6
7
8
int main()
{
	constexpr int MAXSIZE{ 10 };

	int n;
	cin >> n;
	int arr[MAXSIZE], nge[MAXSIZE];
	stack<int> s;


Now that it compiles I will test it shortly and see if I find anything else.

Hope that helps,

Andy
@Handy Andy,
this looks like a problem on codechef or spoj where they use GCC so the use of VLA isn't a problem.
@Thomas1965,

Thank you. That is nice to know.

Andy
Topic archived. No new replies allowed.