Skip to content

Commit 611937e

Browse files
authored
Create 907_Sum_Minimums.py
1 parent 36dee82 commit 611937e

1 file changed

Lines changed: 29 additions & 0 deletions

File tree

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
class Solution:
2+
def sumSubarrayMins(self, arr: list[int]) -> int:
3+
MOD = 10**9 + 7
4+
n = len(arr)
5+
6+
left = [0] * n
7+
right = [0] * n
8+
9+
stack = []
10+
11+
# 왼쪽에서 나보다 작은 값까지의 거리
12+
for i in range(n):
13+
while stack and arr[stack[-1]] > arr[i]:
14+
stack.pop()
15+
16+
left[i] = i - stack[-1] if stack else i + 1
17+
stack.append(i)
18+
19+
stack = []
20+
21+
# 오른쪽에서 나보다 작거나 같은 값까지의 거리
22+
for i in range(n - 1, -1, -1):
23+
while stack and arr[stack[-1]] >= arr[i]:
24+
stack.pop()
25+
26+
right[i] = stack[-1] - i if stack else n - i
27+
stack.append(i)
28+
29+
return sum(arr[i] * left[i] * right[i] for i in range(n)) % MOD

0 commit comments

Comments
 (0)