Skip to content

Commit 0cf7df7

Browse files
authored
Merge pull request #644 from neha030/dev15
Previous Greater Element added
2 parents b11ce05 + d4e5340 commit 0cf7df7

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
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

Comments
 (0)