-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathNextGreaterElementOnRight.java
More file actions
32 lines (29 loc) · 1.04 KB
/
NextGreaterElementOnRight.java
File metadata and controls
32 lines (29 loc) · 1.04 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
import java.util.Arrays;
import java.util.Stack;
public class NextGreaterElementOnRight {
public static void main(String[] args) {
int arr[] = { 20, 7, 5, 14, 16 };
int output[] = new int[arr.length]; // default all are fill with 0
Arrays.fill(output, -1); // all values fill with -1
Stack<Integer> stack = new Stack<>();
stack.push(0); // Store 0th index
for (int i = 1; i < arr.length; i++) {
int index = stack.peek(); // get the top element of stack
if (arr[index] >= arr[i]) {
stack.push(i);
} else {
// Some Greater element found so keep pop the element till u found bigger
// element
while (arr[stack.peek()] < arr[i]) {
output[stack.peek()] = arr[i];
stack.pop();
}
stack.push(i);
}
}
for (int element : output) {
System.out.print(element + " ");
}
System.out.println();
}
}