-
Notifications
You must be signed in to change notification settings - Fork 894
/
Copy pathLongestContinuousSubarrayLimit.swift
41 lines (34 loc) · 1.28 KB
/
LongestContinuousSubarrayLimit.swift
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
/**
* Question Link: https://leetcode.com/problems/longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/
* Primary idea: Slding window, use max and min queues to track largest difference along the way. Move left pointer to get the potential result.
*
* Note: k may be invalid, mention that with interviewer
* Time Complexity: O(n), Space Complexity: O(n)
*
*/
class LongestContinuousSubarrayLimit {
func longestSubarray(_ nums: [Int], _ limit: Int) -> Int {
var maxQueue = [Int](), minQueue = [Int](), left = 0, res = 0
for (i, num) in nums.enumerated() {
while !maxQueue.isEmpty && maxQueue.last! < num {
maxQueue.removeLast()
}
while !minQueue.isEmpty && minQueue.last! > num {
minQueue.removeLast()
}
maxQueue.append(num)
minQueue.append(num)
if maxQueue.first! - minQueue.first! > limit {
if nums[left] == maxQueue.first! {
maxQueue.removeFirst()
}
if nums[left] == minQueue.first! {
minQueue.removeFirst()
}
left += 1
}
res = max(res, i - left + 1)
}
return res
}
}