-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNextGreaterElement.java
More file actions
33 lines (29 loc) · 869 Bytes
/
NextGreaterElement.java
File metadata and controls
33 lines (29 loc) · 869 Bytes
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
package Stacks;
import java.util.Stack;
public class NextGreaterElement {
public static void main(String[] args) {
int[] arr = {6,8,0,1,3};
int[] ans = nextGreater(arr);
for (int i=0; i<arr.length; i++){
System.out.print(ans[i] + " ");
}
}
public static int[] nextGreater(int[] arr) {
Stack<Integer> stack = new Stack<>();
int n = arr.length;
int[] ans = new int[n];
for (int i=n-1; i>=0; i--){
int curr = arr[i];
while (!stack.isEmpty() && curr >= arr[stack.peek()]){
stack.pop();
}
if (stack.isEmpty()) {
ans[i] = -1;
}else {
ans[i] = arr[stack.peek()];
}
stack.push(i);
}
return ans;
}
}