Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- void PrintNge(int arr[], int n) {
- stack<int> s;
- int res[n];
- // start from the back
- for (int i = n - 1; i >= 0; i--) {
- // remove the top element if it's less than the current element
- if (!s.empty()) {
- while (!s.empty() && s.top() <= arr[i]) {
- s.pop();
- }
- }
- // store the next greater element for the current element being iterated upon
- res[i] = s.empty() ? -1 : s.top();
- // push the current element in the stack
- s.push(arr[i]);
- }
- for (int i = 0; i < n; i++) {
- cout << arr[i] << " --> " << res[i] << endl;
- }
- }
- int main() {
- int n;
- cin >> n;
- int arr[n];
- for (int i = 0; i < n; i++) {
- cin >> arr[i];
- }
- PrintNge(arr, n);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement