Skip to content

Commit fd8f081

Browse files
authored
Merge pull request soapyigu#362 from soapyigu/SlidingWindow
Build a sliding window solutions set and add a solution to the Longes…
2 parents adfb981 + c712ca0 commit fd8f081

7 files changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
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+
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy