-
Notifications
You must be signed in to change notification settings - Fork 21.1k
Expand file tree
/
Copy pathMonotonicIncreasingStack.java
More file actions
65 lines (51 loc) · 1.66 KB
/
MonotonicIncreasingStack.java
File metadata and controls
65 lines (51 loc) · 1.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/* Contributor: Nayan Saraff
*
* This Monotonic Increasing Stack is a popular algorithm which helps
* in solving various problems including Stock Span, Trapping Rain Water
*/
import java.util.Arrays;
import java.util.Stack;
public class MonotonicIncreasingStack
{
public static int[] nextGreaterElement(int[] arr)
{
int n = arr.length;
int[] result = new int[n];
Stack<Integer> stack = new Stack<>();
for (int i = n - 1; i >= 0; i--)
{
while (!stack.isEmpty() && arr[i] >= arr[stack.peek()])
{
stack.pop();
}
result[i] = stack.isEmpty() ? -1 : arr[stack.peek()];
stack.push(i);
}
return result;
}
public static int[] nextSmallerElement(int[] arr)
{
int n = arr.length;
int[] result = new int[n];
Stack<Integer> stack = new Stack<>();
for (int i = n - 1; i >= 0; i--)
{
while (!stack.isEmpty() && arr[i] <= arr[stack.peek()])
{
stack.pop();
}
result[i] = stack.isEmpty() ? -1 : arr[stack.peek()];
stack.push(i);
}
return result;
}
public static void main(String[] args)
{
int[] arr = {4, 5, 2, 10, 8};
int[] nextGreater = nextGreaterElement(arr);
int[] nextSmaller = nextSmallerElement(arr);
System.out.println("Next Greater Element: " + Arrays.toString(nextGreater));
System.out.println("Next Smaller Element: " + Arrays.toString(nextSmaller));
}
}
/* Reference: https://www.geeksforgeeks.org/dsa/introduction-to-monotonic-stack-2/ */