702877. Max Score from Subarray Mins
Max Score from Subarray Mins
Slug: max-sum-in-sub-arrays0824
Difficulty: Medium
Id: 702877
Topic Tags: Arrays, Stack, Data Structures
Company Tags: None
Summary
Given an array of integers, find the maximum sum that can be obtained by selecting some subarray and considering only the minimum values in each subarray. For example, if the input array is [3, 1, -1, 6], the maximum sum would be 2 (from subarray [1, -1]).
Detailed Explanation
To solve this problem, we can use a stack-based approach. The idea is to maintain a stack of minimum values seen so far, and for each element in the array, we pop elements from the stack that are greater than or equal to the current element, add their sum to our result, and then push the current element onto the stack.
Here's a step-by-step breakdown:
- Initialize an empty stack
s. - Iterate through the input array
arr:- For each element
xinarr, pop elements fromsthat are greater than or equal tox. Add their sum to our resultres. - Push
xontos.
- For each element
- The final value of
resis the maximum sum we can obtain.
Here's a diagram to illustrate this process:
[3, 1, -1, 6]
s = []
res = 0
for x in arr:
if s and s[-1] >= x:
res += s.pop()
s.append(x)
res = 2 (from subarray [1, -1])
Time complexity: O(n), where n is the length of the input array. We iterate through the array once. Space complexity: O(n), as we need to store all minimum values in our stack.
Optimized Solutions
Java
public int maxSum(int[] arr) {
int res = 0, minSoFar = Integer.MAX_VALUE;
Stack<Integer> s = new Stack<>();
for (int x : arr) {
while (!s.isEmpty() && s.peek() >= x) {
res += s.pop();
}
s.push(x);
minSoFar = Math.min(minSoFar, x);
}
return res;
}