-
Notifications
You must be signed in to change notification settings - Fork 160
/
Copy pathNeargreatestelement.cpp
64 lines (42 loc) · 1.21 KB
/
Neargreatestelement.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
60
61
62
63
64
/*
Given an array, print the Next Greater Element (NGE) for every element.
The Next greater Element for an element x is the first greater element on the right side of x in array.
Elements for which no greater element exist, consider next greater element as -1.
For example:
Input: 11, 13, 21, 3
output: 12, 21, -1, -1
*/
/*
solution: scan the array from right to left. Update current next greater element accordiing to right side original element
and next greater element.
O(n) time, O(1) space
*/
#include<iostream>
#include<algorithm>
using namespace std;
void NextGreaterElement(int arr[], int len, int result[]) {
if (len <= 0) return;
for(int i = len -2; i >= 0; --i){
int maxtwo = max(result[i+1], arr[i+1]);
if (maxtwo <= arr[i]) {
result[i] = -1;
} else {
if (arr[i+1] > arr[i]) {
result[i] = arr[i];
} else if (result[i+1] > arr[i] && arr[i+1] <= arr[i]){
result[i] = result[i+1];
}
}
}
}
int main() {
int arr[]= {11, 13, 21, 3};
int len = sizeof(arr)/sizeof(arr[0]);
int result[] = {-1, -1, -1, -1};
NextGreaterElement(arr, len, result);
for (int i = 0; i< len; ++i) {
cout<<result[i]<<" ";
}
cout<<endl;
return 0;
}