arr[], for every subarray compute the minimum element and return the sum of all those minimums.Example
Input | Output | Explanation |
[10,20] | 40 | Subarrays → (10)=10, (10,20)=10, (20)=20 |
[3,1,2,4] | 17 | Subarrays → minimums: (3)=3, (3,1)=1, (3,1,2)=1, (3,1,2,4)=1, (1)=1, (1,2)=1, (1,2,4)=1, (2)=2, (2,4)=2, (4)=4 |
HINT
For each elementarr[i], how many subarrays havearr[i]as their minimum?
arr[i] × kPrerequisites
Minimum Stack / Minimum Queue - Algorithms for Competitive ProgrammingMinimum Stack / Minimum Queue - Algorithms for Competitive Programming
The goal of this project is to translate the wonderful resource http://e-maxx.ru/algo which provides descriptions of many algorithms and data structures especially popular in field of competitive programming. Moreover we want to improve the collected knowledge by extending the articles and adding new articles to the collection.
LeetCodeMaximum Subarray - LeetCode

Maximum Subarray - LeetCode
Can you solve this real interview question? Maximum Subarray - Given an integer array nums, find the subarray with the largest sum, and return its sum. Example 1: Input: nums = [-2,1,-3,4,-1,2,1,-5,4] Output: 6 Explanation: The subarray [4,-1,2,1] has the largest sum 6. Example 2: Input: nums = [1] Output: 1 Explanation: The subarray [1] has the largest sum 1. Example 3: Input: nums = [5,4,-1,7,8] Output: 23 Explanation: The subarray [5,4,-1,7,8] has the largest sum 23. Constraints: * 1 <= nums.length <= 105 * -104 <= nums[i] <= 104 Follow up: If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
Brute Force
Idea
- Generate every subarray.
- Track the minimum element inside that subarray.
- Add that minimum to the total sum.
arr = [3,1,2]Total: 3 + 1 + 1 + 1 + 1 + 2 = 9Code
C++
Complexity
Metric | Value |
Time Complexity | O(N²) |
Space Complexity | O(1) |
n ≤ 10^5, this approach will not work.Optimal Approach
Key Observation
Count how many subarrays use each element as the minimum.
arr[i] is the minimum in some subarrays, then its total contribution is: arr[i] × number_of_subarrays_where_it_is_minimumIdea
arr[i], determine:arr[i] is the minimum: count = left × right and contribution: arr[i] × left × rightFinding Previous and Next Smaller Elements
O(N) time.Approach
- Compute Previous Smaller Element (PSE).
- Compute Next Smaller Element (NSE).
- For each index:
Code
C++
Java
Python
JavaScript
Complexity Analysis
Metric | Complexity |
Time Complexity | O(N) |
Space Complexity | O(N) |
Conclusion
- Determine how far each element can extend while remaining at a minimum.
- Count how many subarrays use that element as the minimum.
- Multiply by the element value to compute its total contribution.

