Maximum and Minimum Sums of at Most Size K Subarrays - Problem

You are given an integer array nums and a positive integer k.

Return the sum of the maximum and minimum elements of all subarrays with at most k elements.

A subarray is a contiguous non-empty sequence of elements within an array.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,3,2], k = 2
Output: 21
💡 Note: All subarrays: [1] (1+1=2), [3] (3+3=6), [2] (2+2=4), [1,3] (1+3=4), [3,2] (2+3=5). Total: 2+6+4+4+5=21
Example 2 — Single Element
$ Input: nums = [5], k = 1
Output: 10
💡 Note: Only one subarray [5] with min=5, max=5, so sum = 5+5 = 10
Example 3 — Larger k
$ Input: nums = [2,1,4], k = 3
Output: 27
💡 Note: All subarrays: [2](4), [1](2), [4](8), [2,1](3), [1,4](5), [2,1,4](5). Total: 4+2+8+3+5+5=27

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ k ≤ nums.length
  • -104 ≤ nums[i] ≤ 104

Visualization

Tap to expand
Maximum and Minimum Sums of at Most Size K Subarrays INPUT nums array: 1 idx 0 3 idx 1 2 idx 2 k = 2 Valid Subarrays (size 1-2): [1], [3], [2] [1,3], [3,2] 5 subarrays total ALGORITHM STEPS 1 Build Monotonic Stack Track next/prev smaller elements 2 Count Contributions Each element as min/max 3 Apply Size Constraint Limit to subarrays with k elems 4 Sum All Values maxSum + minSum = result Monotonic Stack: decreasing order increasing order O(n) time complexity FINAL RESULT Sum Breakdown: [1]: max=1, min=1 [3]: max=3, min=3 [2]: max=2, min=2 [1,3]: max=3, min=1 [3,2]: max=3, min=2 Max sum: 1+3+2+3+3=12 Min sum: 1+3+2+1+2=9 Output: 21 OK - 12 + 9 = 21 Key Insight: The monotonic stack efficiently finds the range where each element is the maximum or minimum. By constraining subarray size to at most k, we calculate each element's contribution in O(1) time, achieving overall O(n) complexity instead of O(n*k) brute force enumeration. TutorialsPoint - Maximum and Minimum Sums of at Most Size K Subarrays | Monotonic Stack Approach
Asked in
Google 12 Amazon 8 Microsoft 6
12.5K Views
Medium Frequency
~35 min Avg. Time
428 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen