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
Maximum and Minimum Sums: [1,3,2] with k=2[1,3,2]Input ArrayAll subsequences with ≤ 2 elements:[1] → 2[3] → 6[2] → 4[1,3] → 4[1,2] → 3[3,2] → 5Sum: 2 + 6 + 4 + 4 + 3 + 5 = 24Result: 24
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
Asked in
Google 25 Amazon 18 Microsoft 15
12.5K Views
Medium Frequency
~35 min Avg. Time
420 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