Leetcode 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 10^9 + 7.
arr?
30000.arr be negative?
arr are positive integers.To efficiently solve this problem, we’ll employ a stack-based approach to find out how many times each element of the array is the minimum of some subarray.
Previous Less (prev) and Next Less (next). These arrays help to store the distance to the previous and next less element for every element in the array.prev[i] array stores the number of contiguous subarrays ending at index i where arr[i] is the minimum.next[i] array stores the number of contiguous subarrays starting at index i where arr[i] is the minimum value.prev and next arrays to store the lengths of subarrays in terms of indices.prev array.next array, but in a reverse iteration.prev and next.Let’s implement the solution:
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
class Solution {
public:
int sumSubarrayMins(vector<int>& arr) {
int n = arr.size();
vector<int> prev(n), next(n);
stack<int> s;
// Calculate previous less element distances
for (int i = 0; i < n; ++i) {
while (!s.empty() && arr[s.top()] >= arr[i]) {
s.pop();
}
prev[i] = s.empty() ? i + 1 : i - s.top();
s.push(i);
}
while (!s.empty()) s.pop(); // clear the stack
// Calculate next less element distances
for (int i = n - 1; i >= 0; --i) {
while (!s.empty() && arr[s.top()] > arr[i]) {
s.pop();
}
next[i] = s.empty() ? n - i : s.top() - i;
s.push(i);
}
// Calculate result
long long result = 0;
int MOD = 1e9 + 7;
for (int i = 0; i < n; ++i) {
result = (result + (long long)arr[i] * prev[i] * next[i]) % MOD;
}
return result;
}
};
// Example usage:
int main() {
Solution sol;
vector<int> arr = {3, 1, 2, 4};
cout << sol.sumSubarrayMins(arr) << endl; // Output: 17
return 0;
}
O(n), where n is the length of the array. This is because each element is pushed and popped from the stack at most once.O(n), needed for the prev, next, and stack arrays.This solution efficiently computes the sum of the minimums of all subarrays within the constraints provided.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?