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 & Minimum Sums of Subsequences INPUT Array nums: 2 index 0 1 index 1 k = 1 Subsequences with at most k=1 elements: [2] [1] (empty [] excluded) ALGORITHM STEPS 1 Sort Array [2,1] --> [1,2] 2 Count Contributions Each element as max/min 3 Combinatorics Use C(n,r) for subseq For k=1 (single elements): [2]: max=2, min=2 [1]: max=1, min=1 Sum of max: 2+1 = 3 Sum of min: 2+1 = 3 4 Apply Modulo Result % (10^9 + 7) FINAL RESULT Subsequence Analysis: [2]: max + min = 2+2 = 4 [1]: max + min = 1+1 = 2 Total: 4 + 2 = 6 (3 + 3 = 6) Output: 6 OK - Verified Key Insight: For single-element subsequences (k=1), each element is both max and min of itself. Sum of max contributions = 2 + 1 = 3. Sum of min contributions = 2 + 1 = 3. Total = 3 + 3 = 6. For larger k, use combinatorics to count element appearances in subsequences. TutorialsPoint - Maximum and Minimum Sums of at Most Size K Subsequences | Optimal Solution
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