-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy path907-sum-of-subarray-minimums.py
50 lines (45 loc) · 1.7 KB
/
907-sum-of-subarray-minimums.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
class Solution:
def sumSubarrayMins(self, arr: List[int]) -> int:
arr = [0] + arr + [0]
stack = []
res = 0
for i in range(len(arr)):
while stack and arr[stack[- 1]] > arr[i]:
idx = stack.pop()
left_bound = stack[- 1]
right_bound = i
left_choices = idx - left_bound
right_choices = i - idx
res += left_choices * right_choices * arr[idx]
stack.append(i)
return res % (10**9+7)
# time O(n)
# space O(n)
# using stack and queue and montonic and monotonic stack (consider two side’s relationship)
class Solution:
def sumSubarrayMins(self, arr: List[int]) -> int:
smaller_in_right = [len(arr) for _ in range(len(arr))]
stack = []
for i, num in enumerate(arr):
while stack and arr[stack[- 1]] >= num:
idx = stack.pop()
smaller_in_right[idx] = i
stack.append(i)
smaller_in_left = [- 1 for _ in range(len(arr))]
stack = []
for i in range(len(arr) - 1, - 1, - 1):
while stack and arr[stack[- 1]] > arr[i]:
idx = stack.pop()
smaller_in_left[idx] = i
stack.append(i)
res = 0
for i in range(len(arr)):
left_bound = smaller_in_left[i]
right_bound = smaller_in_right[i]
left_choices = i - left_bound
right_choices = right_bound - i
res += left_choices * right_choices * arr[i]
return res % (10**9+7)
# time O(n)
# space O(n)
# using stack and queue and montonic and monotonic stack (consider two side’s relationship)