1
+ /*
2
+ PREVIOUS GREATER ELEMENT USING STACK
3
+
4
+ An Efficient Approach to find Previous Greater Element for every
5
+ element in an array. Given an array of Distinct Integers, find closest
6
+ (Positive-Wise) greater on left of every element. If there is no
7
+ greater element on left then print -1.
8
+ */
9
+
10
+ #include < bits/stdc++.h>
11
+ using namespace std ;
12
+
13
+ /* This function is used to check if top of the
14
+ stack is smaller we remove it or if top is
15
+ greater, then this element is previous greater
16
+ element and print it.
17
+ */
18
+
19
+ void printPrevGreater (int arr[],int n){
20
+ // Stack to store Previous Greater on top of stack.
21
+ stack<int >s;
22
+
23
+ /* Store first element of array to
24
+ check if top item is smaller then
25
+ current item.*/
26
+ s.push (arr[0 ]);
27
+
28
+ /* This loop will help to find the
29
+ previous greater element from
30
+ the current value and simply print
31
+ it and if not found print -1.
32
+ NOTE : After every iteration whaterever the remaining element is
33
+ present at the top is Previous Greater and if stack is empty
34
+ then previous Greater is -1.
35
+ */
36
+ for (int i=0 ;i<n;i++){
37
+ while (s.empty ()==false && s.top ()<=arr[i])
38
+ s.pop ();
39
+
40
+ // pg : Previous Greater
41
+ int pg=s.empty ()?-1 :s.top ();
42
+ cout<<pg<<" " ;
43
+ s.push (arr[i]);
44
+ }
45
+ }
46
+ // Driver's Code
47
+ int main ()
48
+ {
49
+ int n;
50
+ cout<<" Accept the value : " ;
51
+ cin>>n;
52
+ int arr[n];
53
+ cout<<" Accept the array elements : " ;
54
+ for (int i=0 ;i<n;i++){
55
+ cin>>arr[i];
56
+ }
57
+ cout<<" Next Greater Elements : " ;
58
+ printPrevGreater (arr,n);
59
+ return 0 ;
60
+ }
61
+ /*
62
+ INPUT AND OUTPUT
63
+ Accept the value : 5
64
+ Accept the array elements : 20 30 10 5 15
65
+
66
+ Next Greater Elements : -1 -1 30 10 30
67
+
68
+ Time Complexity: O(n)
69
+ */
0 commit comments