File tree 1 file changed +53
-0
lines changed
1 file changed +53
-0
lines changed Original file line number Diff line number Diff line change
1
+ //Program to find next greater number for each element in an array.
2
+ //Next greater element for an element 'x' is first greater element present on the right side of 'x' in the arrau
3
+
4
+
5
+
6
+
7
+ #include <iostream>
8
+ #include <stack>
9
+ using namespace std;
10
+
11
+ int main()
12
+ {
13
+
14
+ int n;
15
+ cin >> n; // n is no of integers
16
+
17
+ int a[n+1];// array for integers
18
+ for(int i=1;i<=n;i++)
19
+ {
20
+ cin >> a[i];
21
+ }
22
+
23
+ stack <int > s;
24
+
25
+ s.push(a[1]);//using stack to keep track of elements whose next greater has not been found
26
+
27
+
28
+ for(int i=2;i<=n;i++)
29
+ {
30
+ while((!s.empty())&&(s.top()<a[i]))
31
+ {
32
+
33
+ cout << "Next Greater element for " << s.top() << " is " << a[i] << endl;
34
+ s.pop();
35
+ }
36
+
37
+ s.push(a[i]);
38
+ }
39
+ while(!s.empty())//elements that are left have no greater element
40
+ {
41
+
42
+ cout << "There is no next greater element of " << s.top() << " in the array " << endl;
43
+ s.pop();
44
+ }
45
+
46
+ //Time Complexity : O(N)
47
+ //Space Complexity: O(N)
48
+
49
+ // where N is number of integers given in the input
50
+
51
+ // Note: You can also find next smallest number ,just by changing the sign '<' to '>' in line 30.
52
+ }
53
+
You can’t perform that action at this time.
0 commit comments