- Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy path_1438.java
33 lines (31 loc) · 1.13 KB
/
_1438.java
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
packagecom.fishercoder.solutions.secondthousand;
importjava.util.PriorityQueue;
publicclass_1438 {
publicstaticclassSolution1 {
/*
* My completely original solution on 1/19/2022.
*/
publicintlongestSubarray(int[] nums, intlimit) {
intans = 0;
PriorityQueue<Integer> maxHeap = newPriorityQueue<>((a, b) -> b - a);
PriorityQueue<Integer> minHeap = newPriorityQueue<>();
for (intleft = 0, right = 0; left < nums.length && right < nums.length; right++) {
if (ans == 0) {
ans = 1;
}
maxHeap.offer(nums[right]);
minHeap.offer(nums[right]);
if (!maxHeap.isEmpty()
&& !minHeap.isEmpty()
&& (maxHeap.peek() - minHeap.peek() <= limit)) {
ans = Math.max(ans, right - left + 1);
} else {
maxHeap.remove(nums[left]);
minHeap.remove(nums[left]);
left++;
}
}
returnans;
}
}
}