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:
36
💡 Note:
All subarrays: [2](4), [1](2), [4](8), [2,1](3), [1,4](5), [2,1,4](6). Total: 4+2+8+3+5+6+8=36
Constraints
- 1 ≤ nums.length ≤ 105
- 1 ≤ k ≤ nums.length
- -104 ≤ nums[i] ≤ 104
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array [1,3,2] with k=2
2
Process
Generate all subarrays of length 1 to k, find their min+max
3
Output
Sum of all min+max values = 21
Key Takeaway
🎯 Key Insight: Use monotonic deques to efficiently track running minimum and maximum in sliding windows
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code