Sponsored
Sponsored
The monotonic stack approach leverages a stack data structure to efficiently determine the minimum element of every subarray. By maintaining indexes and utilizing their properties, we can efficiently compute the sum of all minimum values for the contiguous subarrays.
Time Complexity: O(n), where n is the length of the array.
Space Complexity: O(n), due to the use of auxiliary arrays and a stack.
1const sumSubarrayMins = (arr) => {
2 const MOD = 1e9 + 7;
3 const n = arr.length;
4 const stack = [];
5 let result = 0;
6
7 for (let i = 0; i <= n; i++) {
8 while (stack.length > 0 && (i === n || arr[stack[stack.length - 1]] >= arr[i])) {
9 const curIndex = stack.pop();
10 const curValue = arr[curIndex];
11 const left = stack.length > 0 ? curIndex - stack[stack.length - 1] : curIndex + 1;
12 const right = i - curIndex;
13 result = (result + curValue * left * right) % MOD;
14 }
15 stack.push(i);
16 }
17
18 return result;
19};The JavaScript solution applies similar logic, effectively utilizing an array to serve as a stack, ensuring sequential calculation of array elements’ subarray contributions.
A dynamic programming approach can also be adopted to tackle the given problem. This method involves calculating the contribution of each element to subarray minimums utilizing previously calculated results intelligently.
Time Complexity: O(n)
Space Complexity: O(n), arising from stack usage and dp.
1#include <stack>
using namespace std;
typedef long long ll;
class Solution {
public:
int sumSubarrayMins(vector<int>& arr) {
int MOD = 1e9 + 7;
int n = arr.size();
vector<int> dp(n);
stack<int> s;
ll result = 0;
for (int i = 0; i < n; ++i) {
while (!s.empty() && arr[s.top()] >= arr[i]) s.pop();
int k = (s.empty()) ? i + 1 : i - s.top();
dp[i] = (arr[i] * k + (s.empty() ? 0 : dp[s.top()])) % MOD;
result = (result + dp[i]) % MOD;
s.push(i);
}
return (int)result;
}
};In this C++ solution, a stack maintains previously seen elements, easing computation of minimum contributions by referring to the dp derived from prior computed sections.