Maximum and Minimum Sums of at Most Size K Subsequences - Problem
You are given an integer array nums and a positive integer k.
Return the sum of the maximum and minimum elements of all subsequences of nums with at most k elements.
Since the answer may be very large, return it modulo 109 + 7.
Note: A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [2,1], k = 1
›
Output:
6
💡 Note:
Subsequences of size ≤ 1: [2] gives 2+2=4, [1] gives 1+1=2. Total: 4+2=6
Example 2 — Multiple Sizes
$
Input:
nums = [1,3,2], k = 2
›
Output:
24
💡 Note:
Size 1: [1]→2, [3]→6, [2]→4. Size 2: [1,3]→4, [1,2]→3, [3,2]→5. Total: 2+6+4+4+3+5=24
Example 3 — Edge Case
$
Input:
nums = [5], k = 1
›
Output:
10
💡 Note:
Only one subsequence [5], max=5, min=5, so 5+5=10
Constraints
- 1 ≤ nums.length ≤ 103
- 1 ≤ k ≤ nums.length
- -109 ≤ nums[i] ≤ 109
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array [1,3,2] and k=2
2
Process
Generate all subsequences ≤ size k and find max+min
3
Output
Sum all (max+min) values
Key Takeaway
🎯 Key Insight: Each element contributes predictably as max/min based on its position in sorted order
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code