forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
next_greatest_right.cpp
59 lines (57 loc) · 1.71 KB
/
next_greatest_right.cpp
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/*Next greatest element to the right of each element in the array
ALGORITHM
*Using a stack to find out the next greatest element to the right
*Start the scanning of the array from the right
*Declare an array and a stack
*If the stack is empty, then no element to the right is greater than the present element
*If the stack is not empty but the element present at the top of the stack is not greater than the current element then-
* pop the stack till the stack is not empty or the top element of stack is greater than the current element
*If the stack is not empty and the element at the top of the stack is greater than the current element then push the topmost element to the stack
*/
#include <bits/stdc++.h>
using namespace std;
void nextLargest(int a[], int n)
{
vector<int> v;
stack<int> s;
for (int i = n - 1; i >= 0; i--)
{
if (s.empty() == true)
v.push_back(-1);
else if (s.empty() != true && s.top() > a[i])
v.push_back(s.top());
else if (s.empty() != true && s.top() <= a[i])
{
while (s.top() <= a[i] && s.empty() != true)
{
s.pop();
}
if (s.empty() == true)
v.push_back(-1);
if (s.top() > a[i] && s.empty() != true)
v.push_back(s.top());
}
s.push(a[i]);
}
//reversing the array containing the next greatest element to the right
reverse(v.begin(), v.end());
for (int i = 0; i < n; i++)
cout << v[i] << " ";
}
int main()
{
int n;
cin >> n;
int a[n];
for (int i = 0; i < n; i++)
cin >> a[i];
nextLargest(a, n);
}
/*
INPUT:
n=4
a[n]=1 3 2 4
OUTPUT:
3 4 4 -1
Code Complexity: O(n^2)
*/