Skip to content

Commit c712ca0

Browse files
committed
Build a sliding window solutions set and add a solution to the Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit
1 parent adfb981 commit c712ca0

7 files changed

+41
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/**
2+
* Question Link: https://leetcode.com/problems/longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/description/
3+
* Primary idea: Slding window, use max and min queues to track largest difference along the way. Move left pointer to get the potential result.
4+
*
5+
* Note: k may be invalid, mention that with interviewer
6+
* Time Complexity: O(n), Space Complexity: O(n)
7+
*
8+
*/
9+
10+
class LongestContinuousSubarrayLimit {
11+
func longestSubarray(_ nums: [Int], _ limit: Int) -> Int {
12+
var maxQueue = [Int](), minQueue = [Int](), left = 0, size = 0
13+
14+
for (i, num) in nums.enumerated() {
15+
while !maxQueue.isEmpty && maxQueue.last! < num {
16+
maxQueue.removeLast()
17+
}
18+
while !minQueue.isEmpty && minQueue.last! > num {
19+
minQueue.removeLast()
20+
}
21+
22+
maxQueue.append(num)
23+
minQueue.append(num)
24+
25+
if maxQueue.first! - minQueue.first! > limit {
26+
if nums[left] == maxQueue.first! {
27+
maxQueue.removeFirst()
28+
}
29+
if nums[left] == minQueue.first! {
30+
minQueue.removeFirst()
31+
}
32+
33+
left += 1
34+
}
35+
36+
size = max(size, i - left + 1)
37+
}
38+
39+
return size
40+
}
41+
}
File renamed without changes.
File renamed without changes.

0 commit comments

Comments
 (0)