-
Notifications
You must be signed in to change notification settings - Fork 65
Expand file tree
/
Copy path2104-sum-of-subarray-ranges.py
More file actions
26 lines (25 loc) · 1023 Bytes
/
Copy path2104-sum-of-subarray-ranges.py
File metadata and controls
26 lines (25 loc) · 1023 Bytes
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
class Solution:
def subArrayRanges(self, nums: List[int]) -> int:
res = 0
temp = [float('inf')] + nums + [float('inf')]
stack = []
for i in range(len(temp)):
while stack and temp[stack[- 1]] < temp[i]:
idx = stack.pop()
left_bound = stack[- 1]
right_bound = i
res += (idx - left_bound) * (right_bound - idx) * temp[idx]
stack.append(i)
temp = [float('-inf')] + nums + [float('-inf')]
stack = []
for i in range(len(temp)):
while stack and temp[stack[- 1]] > temp[i]:
idx = stack.pop()
left_bound = stack[- 1]
right_bound = i
res -= (idx - left_bound) * (right_bound - idx) * temp[idx]
stack.append(i)
return res
# time O(n), due to traverse twice
# space O(n), due to stack
# using stack and queue and montonic and monotonic stack (consider two side’s relationship)