Skip to content

Commit fc51128

Browse files
authored
Create 907. Sum of Subarray Minimums.py
1 parent dbdff9a commit fc51128

1 file changed

Lines changed: 37 additions & 0 deletions

File tree

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
'''
2+
1. 아이디어 :
3+
최대 nlogn 시간복잡도로 문제를 풀어야한다. (캐싱 또는 DP로 값 재사용)
4+
i보다 왼쪽에 있는 인덱스 j 중, arr[i]보다 작은 arr[j]의 위치를 구한다. (monotonic stack)
5+
dp[i]는 0~i까지 윈도우를 설정했을때의 총합을 유지.
6+
j value를 포함하는 윈도우는 0~j까지의 합을 미리 구했기때문에 i-j 범위 * arr[i]
7+
8+
2. 시간복잡도 :
9+
O(2n)
10+
11+
3. 자료구조/알고리즘 :
12+
dp + monotonic stack
13+
14+
'''
15+
class Solution:
16+
def sumSubarrayMins(self, arr: List[int]) -> int:
17+
MOD = 1000000007
18+
n = len(arr)
19+
20+
dp = [0] * n
21+
small_indexes = []
22+
23+
for i in range(n):
24+
cval = arr[i]
25+
while small_indexes and arr[small_indexes[-1]] > cval:
26+
small_indexes.pop()
27+
28+
if small_indexes:
29+
j = small_indexes[-1]
30+
dp[i] = dp[j] + cval * (i-j)
31+
else:
32+
dp[i] = cval * (i+1)
33+
34+
small_indexes.append(i)
35+
36+
return sum(dp) % MOD
37+

0 commit comments

Comments
 (0)