-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathm1438 Daily.java
46 lines (38 loc) · 1.46 KB
/
m1438 Daily.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
34
35
36
37
38
39
40
41
42
43
44
45
46
class Solution {
public int longestSubarray(int[] nums, int limit) {
int output = 0;
PriorityQueue<Pair<Integer, Integer>> max = new PriorityQueue<>(Comparator.comparing(Pair::getValue)); // * -1
PriorityQueue<Pair<Integer, Integer>> min = new PriorityQueue<>(Comparator.comparing(Pair::getValue)); // Default min
int indxLeft = 0;
int indexRight = 0;
while (indexRight < nums.length) {
max.add(new Pair<>(indexRight, -1 * nums[indexRight]));
min.add(new Pair<>(indexRight, nums[indexRight]));
while (max.peek().getKey() < indxLeft) {
max.remove();
}
while (min.peek().getKey() < indxLeft) {
min.remove();
}
int maxVal = -1 * max.peek().getValue();
int maxIndx = max.peek().getKey();
int minVal = min.peek().getValue();
int minIndx = min.peek().getKey();
if (maxVal - minVal > limit) {
if (maxIndx > minIndx) {
indxLeft = minIndx + 1;
continue;
} else {
indxLeft = maxIndx + 1;
continue;
}
} else {
if (indexRight - indxLeft + 1 > output) {
output = indexRight - indxLeft + 1;
}
indexRight++;
}
}
return output;
}
}