Advertisement
jasonpogi1669

Next Greater Element using Stack in C++

Dec 17th, 2021
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.73 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. void PrintNge(int arr[], int n) {
  6.     stack<int> s;
  7.     int res[n];
  8.     // start from the back
  9.     for (int i = n - 1; i >= 0; i--) {
  10.         // remove the top element if it's less than the current element
  11.         if (!s.empty()) {
  12.             while (!s.empty() && s.top() <= arr[i]) {
  13.                 s.pop();
  14.             }
  15.         }
  16.         // store the next greater element for the current element being iterated upon
  17.         res[i] = s.empty() ? -1 : s.top();
  18.         // push the current element in the stack
  19.         s.push(arr[i]);
  20.     }
  21.     for (int i = 0; i < n; i++) {
  22.         cout << arr[i] << " --> " << res[i] << endl;
  23.     }
  24. }
  25.  
  26. int main() {
  27.     int n;
  28.     cin >> n;
  29.     int arr[n];
  30.     for (int i = 0; i < n; i++) {
  31.         cin >> arr[i];
  32.     }
  33.     PrintNge(arr, n);
  34.     return 0;
  35. }
  36.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement