702877. Max Score from Subarray Mins

Medium

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:

  1. Initialize an empty stack s.
  2. Iterate through the input array arr:
    • For each element x in arr, pop elements from s that are greater than or equal to x. Add their sum to our result res.
    • Push x onto s.
  3. The final value of res is 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

View on GeeksforGeeks
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;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.