-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAdditional3.cpp
More file actions
42 lines (34 loc) · 876 Bytes
/
Copy pathAdditional3.cpp
File metadata and controls
42 lines (34 loc) · 876 Bytes
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
#include <iostream>
#include <stack>
using namespace std;
int main() {
int n;
cout << "Enter size of array: ";
cin >> n;
int arr[n];
cout << "Enter elements:\n";
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
int nge[n]; // to store answers
stack<int> s; // will store indices
// Traverse from right to left
for (int i = n - 1; i >= 0; i--) {
// remove smaller elements
while (!s.empty() && s.top() <= arr[i]) {
s.pop();
}
if (s.empty()) {
nge[i] = -1;
} else {
nge[i] = s.top();
}
// push current element
s.push(arr[i]);
}
cout << "Next Greater Elements:\n";
for (int i = 0; i < n; i++) {
cout << arr[i] << " -> " << nge[i] << endl;
}
return 0;
}