1
- /*Contributor: Nayan Saraff
1
+ /* Contributor: Nayan Saraff
2
+ *
3
+ * This Monotonic Increasing Stack is a popular algorithm which helps
4
+ * in solving various problems including Stock Span, Trapping Rain Water
5
+ */
2
6
3
- This Monotonic Increasing Stack is a popular algorithm which helps
4
- in solving various problems including the Stock Span, Trapping Rain water*/
7
+ import java . util . Arrays ;
8
+ import java . util . Stack ;
5
9
10
+ public class MonotonicIncreasingStack
11
+ {
6
12
7
- import java .util .*;
8
-
9
- public class MonotonicIncreasingStack {
10
-
11
- // Returns Next Greater Element for each element in the array
12
- public static int [] nextGreaterElement (int [] arr ) {
13
+ public static int [] nextGreaterElement (int [] arr )
14
+ {
13
15
int n = arr .length ;
14
16
int [] result = new int [n ];
15
- Stack <Integer > stack = new Stack <>(); // stores indices
17
+ Stack <Integer > stack = new Stack <>();
16
18
17
- for (int i = n - 1 ; i >= 0 ; i --) {
18
- // Pop elements smaller or equal to arr[i]
19
- while (!stack .isEmpty () && arr [i ] >= arr [stack .peek ()]) {
19
+ for (int i = n - 1 ; i >= 0 ; i --)
20
+ {
21
+ while (!stack .isEmpty () && arr [i ] >= arr [stack .peek ()])
22
+ {
20
23
stack .pop ();
21
24
}
22
25
23
- // If stack is empty, no greater element to the right
24
26
result [i ] = stack .isEmpty () ? -1 : arr [stack .peek ()];
25
-
26
- // Push current index onto stack
27
27
stack .push (i );
28
28
}
29
29
30
30
return result ;
31
31
}
32
32
33
- // Returns Next Smaller Element for each element in the array
34
- public static int [] nextSmallerElement ( int [] arr ) {
33
+ public static int [] nextSmallerElement ( int [] arr )
34
+ {
35
35
int n = arr .length ;
36
36
int [] result = new int [n ];
37
- Stack <Integer > stack = new Stack <>(); // stores indices
37
+ Stack <Integer > stack = new Stack <>();
38
38
39
- for (int i = n - 1 ; i >= 0 ; i --) {
40
- // Pop elements greater or equal to arr[i]
41
- while (!stack .isEmpty () && arr [i ] <= arr [stack .peek ()]) {
39
+ for (int i = n - 1 ; i >= 0 ; i --)
40
+ {
41
+ while (!stack .isEmpty () && arr [i ] <= arr [stack .peek ()])
42
+ {
42
43
stack .pop ();
43
44
}
44
45
@@ -49,7 +50,8 @@ public static int[] nextSmallerElement(int[] arr) {
49
50
return result ;
50
51
}
51
52
52
- public static void main (String [] args ) {
53
+ public static void main (String [] args )
54
+ {
53
55
int [] arr = {4 , 5 , 2 , 10 , 8 };
54
56
55
57
int [] nextGreater = nextGreaterElement (arr );
@@ -60,4 +62,4 @@ public static void main(String[] args) {
60
62
}
61
63
}
62
64
63
- /* https://www.geeksforgeeks.org/dsa/introduction-to-monotonic-stack-2/ */
65
+ /* Reference: https://www.geeksforgeeks.org/dsa/introduction-to-monotonic-stack-2/ */
0 commit comments