Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit LeetCode solution in Java

1
class Solution {
2

3
public int longestSubarray(int[] nums, int limit) {
4

5
Deque<Integer> increasing = new LinkedList<Integer>(); // To keep track of Max_value index
6
Deque<Integer> decreasing = new LinkedList<Integer>(); // To keep track of Min_value index
7

8
int i = 0;
9
int j = 0;
10
int max_length = 0;
11

12
while (j < nums.length) {
13

14
while (!increasing.isEmpty() && nums[increasing.peekLast()] >= nums[j]) {
15
increasing.pollLast();
16
}
17

18
increasing.add(j);
19

20
while (!decreasing.isEmpty() && nums[decreasing.peekLast()] <= nums[j]) {
21
decreasing.pollLast();
22
}
23

24
decreasing.add(j);
25

26
int max_val = nums[decreasing.peekFirst()];
27
int min_val = nums[increasing.peekFirst()];
28

29
if (max_val - min_val <= limit) {
30
max_length = Math.max(max_length, j - i + 1);
31
} else {
32

33
// If maximum absolute diff > limit , then remove from dequeue and increase i
34
while (i <= j && nums[decreasing.peekFirst()] - nums[increasing.peekFirst()] > limit) {
35

36
if (!increasing.isEmpty() && increasing.peekFirst() == i) {
37
increasing.pollFirst();
38
}
39

40
if (!decreasing.isEmpty() && decreasing.peekFirst() == i) {
41
decreasing.pollFirst();
42
}
43

44
i++;
45
}
46
}
47

48
j++;
49
}
50

51
return max_length;
52
}
53
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0