-
Notifications
You must be signed in to change notification settings - Fork 65
Expand file tree
/
Copy pathNextGreaterElement.java
More file actions
33 lines (27 loc) · 938 Bytes
/
NextGreaterElement.java
File metadata and controls
33 lines (27 loc) · 938 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
import java.util.*;
public class NextGreaterElement {
public static void main(String[] args) {
int[] nums = {4, 5, 2, 25};
int[] result = findNextGreaterElements(nums);
System.out.println("Next Greater Elements:");
for (int val : result) {
System.out.print(val + " ");
}
}
public static int[] findNextGreaterElements(int[] nums) {
int n = nums.length;
int[] nextGreater = new int[n];
Stack<Integer> stack = new Stack<>();
for (int i = n - 1; i >= 0; i--) {
// Pop smaller elements
while (!stack.isEmpty() && stack.peek() <= nums[i]) {
stack.pop();
}
// If stack is empty, no greater element
nextGreater[i] = stack.isEmpty() ? -1 : stack.peek();
// Push current element
stack.push(nums[i]);
}
return nextGreater;
}
}