Medium
,Array
,DP
,Stack
Given an array of integers arr, find the sum of min(b)
, where b
ranges over every (contiguous) subarray of arr
. Since the answer may be large, return the answer modulo
Input: arr = [3,1,2,4]
Output: 17
Explanation:
Subarrays are [3], [1], [2], [4], [3,1], [1,2], [2,4], [3,1,2], [1,2,4], [3,1,2,4].
Minimums are 3, 1, 2, 4, 1, 1, 2, 1, 1, 1.
Sum is 17.
Input: arr = [11,81,94,43,3]
Output: 444
Constraints:
1 <= arr.length
<= 1 <= arr[i]
<=
class Solution:
def sumSubarrayMins(self, arr: List[int]) -> int:
arr = [0] + arr
stack = [0]
dp = [0] * len(arr)
for i, n in enumerate(arr):
while arr[stack[-1]] > n:
stack.pop()
j = stack[-1]
dp[i] = dp[j] + (i-j) * n
stack.append(i)
return sum(dp) % 1000000007
Yen-Chi ChenFri, Nov 25, 2022 10:40 PM
class Solution:
def sumSubarrayMins(self, arr: List[int]) -> int:
res = 0
stack = []
arr = [0] + arr + [0]
for idx, num in enumerate(arr):
while stack and arr[stack[-1]] > num:
cur = stack.pop()
res += arr[cur] * (idx-cur) * (cur-stack[-1])
stack.append(idx)
return res% (10**9+7)
DanSat, Jan 20, 2024 08:03 PM
class Solution {
public:
int sumSubarrayMins(vector<int>& arr) {
stack<int> s;
vector<int> dp(arr.size());
for (int i = 0; i < arr.size(); i++) {
int n = arr[i];
while(!s.empty() && arr[s.top()] >= n) {
s.pop();
}
if (s.empty()) {
dp[i] = (i + 1) * n;
} else {
int j = s.top();
dp[i] = dp[j] + (i - j) * n;
}
s.push(i);
}
int result = 0;
for (auto t : dp) {
result = (result + t) % 1000000007;
}
return result;
}
};
Time:
Extra Space:
Yen-Chi ChenFri, Nov 25, 2022 10:40 PM