-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDay18.java
More file actions
37 lines (28 loc) · 1.11 KB
/
Day18.java
File metadata and controls
37 lines (28 loc) · 1.11 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
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
import java.util.*;
public class Day18 {
public int[] nextGreaterElements(int[] nums) {
int n = nums.length;
int[] result = new int[n];
Stack<Integer> stack = new Stack<>();
Map<Integer, Integer> nextGreaterMap = new HashMap<>();
for (int i = 2 * n - 1; i >= 0; i--) {
while (!stack.isEmpty() && nums[stack.peek()] <= nums[i % n]) {
stack.pop();
}
result[i % n] = stack.isEmpty() ? -1 : nums[stack.peek()];
nextGreaterMap.put(i % n, result[i % n]);
stack.push(i % n);
}
return result;
}
public static void main(String[] args) {
Day18 nextGreaterElement = new Day18();
int[] nums = {4, 2, 10, 8, 1, 6};
int[] result = nextGreaterElement.nextGreaterElements(nums);
System.out.println("Next Greater Elements for the array: " + java.util.Arrays.toString(nums));
System.out.println("Result: " + java.util.Arrays.toString(result));
}
}