题目描述
给定一个整数数组 A,找到 min(B) 的总和,其中 B 的范围为 A 的每个(连续)子数组。
由于答案可能很大,因此返回答案模 10^9 + 7。
示例:
输入:[3,1,2,4]
输出:17
解释:
子数组为 [3],[1],[2],[4],[3,1],[1,2],[2,4],[3,1,2],[1,2,4],[3,1,2,4]。
最小值为 3,1,2,4,1,1,2,1,1,1,和为 17。
Sample & Demo Code 1
class Solution {
public int sumSubarrayMins(int[] A) {
int[] leftNum = new int[A.length];
int[] rightNum = new int[A.length];
for(int i = 0; i < A.length; i++) {
int count = 1;
// 这里的A[j] > A[i]和下面A[j] >= A[i] 其中一个是 >= ,就行(只能有一个 >=,即有两个相等的时,在向左或者向右寻找 子数组的最小值时,可以任取一个,但要一直选同一个)
for(int j = i - 1; j >= 0 && A[j] > A[i]; ) {
count += leftNum[j];
j -= leftNum[j];
}
leftNum[i] = count;
}
for(int i = A.length-1; i >= 0; i--) {
int count = 1;
for(int j = i + 1; j < A.length && A[j] >= A[i]; ) {
count += rightNum[j];
j += rightNum[j];
}
rightNum[i] = count;
}
int res = 0;
for(int i = 0; i < A.length; i++) {
res += (A[i] * leftNum[i] * rightNum[i]) % (1000000007);
res %= 1000000007;
}
return res;
}
}
Sample & Demo Code 2
单调栈,一次遍历(同时也有点像dp)
用list保存累加的结果 if(pos != -1),这里就是判断需不需要累加,遇到当前数组最小的话会清空stack,导致pos == -1,然后这个最小值的结果会累加保存到后面的数的list[i]位置。
class Solution {
public int sumSubarrayMins(int[] A) {
Stack<Integer> stack = new Stack<>();
int[] list = new int[A.length];
for(int i = 0; i < A.length; i++) {
int pos;
while(!stack.isEmpty() && A[stack.peek()] >= A[i])
stack.pop();
if(stack.isEmpty()) pos = -1;
else pos = stack.peek();
stack.push(i);
if(pos != -1)
list[i] = list[pos];
list[i] += A[i] * (i-pos) % 1000000007;
}
int res = 0;
for(int i : list)
res = (res+i) % 1000000007;
return res;
}
}
Sample Code
和上面代码思路相同, 不过是用构造了一个类来实现。
class Solution {
public int sumSubarrayMins(int[] A) {
int MOD = 1000000007;
Stack<RepInteger> stack = new Stack();
int ans = 0, dot = 0;
for (int j = 0; j < A.length; ++j) {
// Add all answers for subarrays [i, j], i <= j
int count = 1;
while (!stack.isEmpty() && stack.peek().val >= A[j]) {
RepInteger node = stack.pop();
count += node.count;
dot -= node.val * node.count;
}
stack.push(new RepInteger(A[j], count));
dot += A[j] * count;
ans += dot;
ans %= MOD;
}
return ans;
}
}
class RepInteger {
int val, count;
RepInteger(int v, int c) {
val = v;
count = c;
}
}
来源:力扣(LeetCode)
图片作者:smoon1989
https://leetcode-cn.com/problems/sum-of-subarray-minimums
https://leetcode-cn.com/problems/sum-of-subarray-minimums/solution/dan-diao-zhan-python3-by-smoon1989/