Skip to content

Commit

Permalink
Merge pull request soapyigu#362 from soapyigu/SlidingWindow
Browse files Browse the repository at this point in the history
Build a sliding window solutions set and add a solution to the Longes…
  • Loading branch information
soapyigu authored Oct 6, 2022
2 parents adfb981 + c712ca0 commit fd8f081
Show file tree
Hide file tree
Showing 7 changed files with 41 additions and 0 deletions.
41 changes: 41 additions & 0 deletions SlidingWindow/LongestContinuousSubarrayLimit.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
/**
* Question Link: https://leetcode.com/problems/longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/description/
* 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, size = 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
}

size = max(size, i - left + 1)
}

return size
}
}
File renamed without changes.
File renamed without changes.
File renamed without changes.

0 comments on commit fd8f081

Please sign in to comment.