-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathmaximum-and-minimum-sums-of-at-most-size-k-subarrays.py
69 lines (60 loc) · 2.08 KB
/
maximum-and-minimum-sums-of-at-most-size-k-subarrays.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
61
62
63
64
65
66
67
68
69
# Time: O(n)
# Space: O(k)
import collections
# two pointers, sliding window, mono deque
class Solution(object):
def minMaxSubarraySum(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
def count(check):
result = total = 0
dq = collections.deque()
for right in xrange(len(nums)):
while dq and not check(nums[dq[-1]], nums[right]):
i = dq.pop()
cnt = i-(dq[-1]+1 if dq else max(right-k+1, 0))+1
total -= cnt*nums[i]
cnt = right-(dq[-1]+1 if dq else max(right-k+1, 0))+1
dq.append(right)
total += cnt*nums[right]
result += total
if right-(k-1) >= 0:
total -= nums[dq[0]]
if dq[0] == right-(k-1):
dq.popleft()
return result
return count(lambda a, b: a < b)+count(lambda a, b: a > b)
# Time: O(n)
# Space: O(k)
import collections
# two pointers, sliding window, mono deque
class Solution2(object):
def minMaxSubarraySum(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
def count(check):
result = total = 0
dq = collections.deque()
for right in xrange(len(nums)):
left = right
while dq and not check(nums[dq[-1][0]], nums[right]):
i, left = dq.pop()
total -= (i-left+1)*nums[i]
dq.append([right, left])
total += (right-left+1)*nums[right]
result += total
if right-(k-1) >= 0:
total -= nums[dq[0][0]]
if dq[0][0] == right-(k-1):
dq.popleft()
else:
assert(dq[0][1] == right-(k-1))
dq[0][1] += 1
return result
return count(lambda a, b: a < b)+count(lambda a, b: a > b)