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.
1using System;
2using System.Collections.Generic;
3
4public class Solution {
5 public int SumSubarrayMins(int[] arr) {
6 const int MOD = (int)1e9 + 7;
7 int n = arr.Length;
8 Stack<int> stack = new Stack<int>();
9 long sum = 0;
10
11 for (int i = 0; i <= n; i++) {
12 while (stack.Count > 0 && (i == n || arr[stack.Peek()] >= arr[i])) {
13 int index = stack.Pop();
14 int curValue = arr[index];
15 int left = stack.Count == 0 ? index + 1 : index - stack.Peek();
16 int right = i - index;
17 sum = (sum + (long)curValue * left * right) % MOD;
18 }
19 stack.Push(i);
20 }
21
22 return (int)sum;
23 }
24}This C# solution centers around a stack to calculate the minimum contributions strategically and efficiently, considering combinations from both sides.
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.
1def
Through dynamic programming, this Python solution consolidates subarray results iteratively, using an array dp to track cumulative outcomes efficiently.