[LeetCode] Sum of Subarray Minimums

907. Sum of Subarray Minimums

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 109 + 7.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
private:
int getJump(vector<int>& arr, vector<int>& jump, int cur) {
int start = cur + 1;
while(start < arr.size() && arr[cur] <= arr[start]) {
start += jump[start];
}
return start - cur;
}

public:
int sumSubarrayMins(vector<int>& arr) {
vector<int> jump(arr.size() + 1, 0);
vector<int> memo(arr.size() + 1, 0);
int res = 0;
int mod = 1e9 + 7;
for(int i = arr.size() - 1; i >= 0; --i) {
jump[i] = getJump(arr, jump, i);
res += (memo[i] = (arr[i] * jump[i] + memo[i + jump[i]]) % mod);
res %= mod;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/02/20/PS/LeetCode/sum-of-subarray-minimums/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.