forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit.py
60 lines (53 loc) · 1.77 KB
/
longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit.py
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# Time: O(n)
# Space: O(n)
import collections
class Solution(object):
def longestSubarray(self, nums, limit):
"""
:type nums: List[int]
:type limit: int
:rtype: int
"""
max_dq, min_dq = collections.deque(), collections.deque()
left = 0
for right, num in enumerate(nums):
while max_dq and nums[max_dq[-1]] <= num:
max_dq.pop()
max_dq.append(right)
while min_dq and nums[min_dq[-1]] >= num:
min_dq.pop()
min_dq.append(right)
if nums[max_dq[0]]-nums[min_dq[0]] > limit:
if max_dq[0] == left:
max_dq.popleft()
if min_dq[0] == left:
min_dq.popleft()
left += 1 # advance left by one to not count in result
return len(nums)-left
# Time: O(n)
# Space: O(n)
import collections
class Solution2(object):
def longestSubarray(self, nums, limit):
"""
:type nums: List[int]
:type limit: int
:rtype: int
"""
max_dq, min_dq = collections.deque(), collections.deque()
result, left = 0, 0
for right, num in enumerate(nums):
while max_dq and nums[max_dq[-1]] <= num:
max_dq.pop()
max_dq.append(right)
while min_dq and nums[min_dq[-1]] >= num:
min_dq.pop()
min_dq.append(right)
while nums[max_dq[0]]-nums[min_dq[0]] > limit: # both always exist "right" element
if max_dq[0] == left:
max_dq.popleft()
if min_dq[0] == left:
min_dq.popleft()
left += 1
result = max(result, right-left+1)
return result