Maximum and Minimum Sums of at Most Size K Subsequences - Problem
You're given an integer array nums and a positive integer k. Your task is to find the sum of maximum and minimum elements from all possible subsequences that have at most k elements.

A subsequence is a sequence that can be derived from the array by deleting some or no elements without changing the order of the remaining elements. For example, from array [3,1,4], valid subsequences include [3], [1,4], [3,1,4], etc.

For each valid subsequence, you need to:
• Find its maximum element
• Find its minimum element
• Add both to your running total

Since the answer can be very large, return it modulo 109 + 7.

Example: For nums = [1,2,3] and k = 2:
• Subsequence [1]: max=1, min=1, contributes 2
• Subsequence [2]: max=2, min=2, contributes 4
• Subsequence [3]: max=3, min=3, contributes 6
• Subsequence [1,2]: max=2, min=1, contributes 3
• Subsequence [1,3]: max=3, min=1, contributes 4
• Subsequence [2,3]: max=3, min=2, contributes 5
Total: 2+4+6+3+4+5 = 24

Input & Output

example_1.py — Python
$ Input: nums = [1, 2, 3], k = 2
Output: 24
💡 Note: Valid subsequences: [1]→2, [2]→4, [3]→6, [1,2]→3, [1,3]→4, [2,3]→5. Total: 2+4+6+3+4+5=24
example_2.py — Python
$ Input: nums = [5, -2], k = 1
Output: 6
💡 Note: Valid subsequences: [5]→10, [-2]→-4. Total: 10+(-4)=6
example_3.py — Python
$ Input: nums = [1], k = 1
Output: 2
💡 Note: Only one subsequence [1] with max=1, min=1. Total: 1+1=2

Constraints

  • 1 ≤ nums.length ≤ 20
  • 1 ≤ k ≤ nums.length
  • -105 ≤ nums[i] ≤ 105
  • Answer fits in 32-bit signed integer after taking modulo

Visualization

Tap to expand
🏆 Tournament Prize DistributionPlayers: [1, 2, 3], Max Team Size: 21Rookie PlayerTeams as Star: {1} → 1 teamTeams as Rookie: {1}, {1,2}, {1,3} → 3 teamsPrize: 1 × (1+3) = 42Mid PlayerTeams as Star: {2}, {1,2} → 2 teamsTeams as Rookie: {2}, {2,3} → 2 teamsPrize: 2 × (2+2) = 83Star PlayerTeams as Star: {3}, {1,3}, {2,3} → 3 teamsTeams as Rookie: {3} → 1 teamPrize: 3 × (3+1) = 12🎯 Total Prize Money4 + 8 + 12 = 24Mathematical insight: Each element's contribution = value × (max_appearances + min_appearances)
Understanding the Visualization
1
Rank Players
Sort players by skill level: [1, 2, 3]
2
Calculate Championships
For each player, count teams where they're the star (highest) or rookie (lowest)
3
Distribute Prizes
Multiply each player's score by number of teams they impact
4
Sum Total
Add all prize money: 4 + 8 + 12 = 24
Key Takeaway
🎯 Key Insight: Instead of generating all subsequences, calculate each element's total impact using its position in the sorted array and combinatorial formulas.
Asked in
Google 35 Meta 28 Amazon 22 Microsoft 18
28.9K Views
Medium Frequency
~25 min Avg. Time
847 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