LeetCode 907: Sum of Subarray Minimums Solution
Master LeetCode problem 907 (Sum of Subarray Minimums), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
907. Sum of Subarray Minimums
Problem Explanation
Explanation
To solve this problem, we can use a monotonic stack approach. The key idea is to find the number of subarrays where the current element is the minimum element. We can achieve this by maintaining two arrays, left and right, which store the number of consecutive elements greater than or equal to the current element on the left and right sides, respectively.
By using the monotonic stack, we can efficiently calculate these two arrays. Then, we can calculate the contribution of each element to the final result based on the number of subarrays where it is the minimum element.
Finally, we sum up all the contributions to get the total sum of minimums modulo 10^9 + 7.
- Time complexity: O(N), where N is the number of elements in the input array.
- Space complexity: O(N).
Solution Code
class Solution {
public int sumSubarrayMins(int[] arr) {
int MOD = 1000000007;
int n = arr.length;
int[] left = new int[n];
int[] right = new int[n];
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < n; i++) {
while (!stack.isEmpty() && arr[i] <= arr[stack.peek()]) {
stack.pop();
}
left[i] = stack.isEmpty() ? i + 1 : i - stack.peek();
stack.push(i);
}
stack.clear();
for (int i = n - 1; i >= 0; i--) {
while (!stack.isEmpty() && arr[i] < arr[stack.peek()]) {
stack.pop();
}
right[i] = stack.isEmpty() ? n - i : stack.peek() - i;
stack.push(i);
}
long result = 0;
for (int i = 0; i < n; i++) {
result = (result + (long)arr[i] * left[i] * right[i]) % MOD;
}
return (int) result;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 907 (Sum of Subarray Minimums)?
This page provides optimized solutions for LeetCode problem 907 (Sum of Subarray Minimums) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 907 (Sum of Subarray Minimums)?
The time complexity for LeetCode 907 (Sum of Subarray Minimums) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 907 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 907 in Java, C++, or Python.