1
1
package me .ramswaroop .arrays ;
2
2
3
- import java .util .Arrays ;
3
+ import me .ramswaroop .common .LinkedStack ;
4
+ import me .ramswaroop .common .Stack ;
4
5
5
6
/**
6
7
* Created by IntelliJ IDEA.
@@ -19,22 +20,41 @@ public class NextGreaterElement {
19
20
* @param a
20
21
* @return
21
22
*/
22
- public static int [] nextGreaterElements (int [] a ) {
23
- int [] greaterElements = new int [ a . length ]; // stores the next greater element of each element in array a
24
- greaterElements [ a . length - 1 ] = - 1 ; // no elements greater than the last element
23
+ public static void nextGreaterElements (int [] a ) {
24
+ int i = 0 ;
25
+ Stack < Integer > stack = new LinkedStack <>() ; // used to store elements whose NGE is yet to be determined
25
26
26
- for (int i = a .length - 2 ; i >= 0 ; i --) {
27
- if (a [i + 1 ] > a [i ]) { // if next element is greater than the current element
28
- greaterElements [i ] = a [i + 1 ];
29
- } else { // if next element is smaller then find the greater element of the next element
30
- greaterElements [i ] = greaterElements [i + 1 ];
27
+ for (; i < a .length - 1 ; i ++) {
28
+ stack .push (a [i ]);
29
+
30
+ while (!stack .isEmpty ()) {
31
+ Integer pop = stack .pop ();
32
+ if (pop < a [i + 1 ]) { // NGE found for popped element
33
+ System .out .println (pop + "->" + a [i + 1 ]);
34
+ } else {
35
+ stack .push (pop ); // NGE still not found for popped element, so push it again
36
+ break ;
37
+ }
31
38
}
32
39
}
33
- return greaterElements ;
40
+
41
+ // no NGE for elements left in stack
42
+ while (!stack .isEmpty ()) {
43
+ System .out .println (stack .pop () + "->" + -1 );
44
+ }
45
+
46
+ // no NGE for last element
47
+ System .out .println (a [i ] + "->" + -1 );
34
48
}
35
49
36
50
public static void main (String a []) {
37
- System .out .println (Arrays .toString (nextGreaterElements (new int []{4 , 5 , 2 , 25 })));
38
- System .out .println (Arrays .toString (nextGreaterElements (new int []{11 , 13 , 21 , 3 })));
51
+ int [] ar = new int []{4 , 5 , 2 , 25 };
52
+ nextGreaterElements (ar );
53
+ System .out .println ("=========" );
54
+ ar = new int []{11 , 13 , 21 , 3 };
55
+ nextGreaterElements (ar );
56
+ System .out .println ("=========" );
57
+ ar = new int []{1 , 5 , 3 , 4 , 2 , 0 , 11 };
58
+ nextGreaterElements (ar );
39
59
}
40
60
}
0 commit comments