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
This C solution uses an array dp to compute subarray minimum sums progressively, allowing each integer's effect to persist cumulatively across numerous subarray possibilities.