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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code