Find Subsequence of Length K With the Largest Sum - Problem

You are given an integer array nums and an integer k. You want to find a subsequence of nums of length k that has the largest sum.

Return any such subsequence as an integer array of length k.

A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.

Input & Output

Example 1 — Basic Case
$ Input: nums = [2,1,3,1], k = 2
Output: [2,3]
💡 Note: The subsequence has the largest sum among all subsequences of length 2. We select the largest values 3 and 2 while maintaining their original order.
Example 2 — All Positive Numbers
$ Input: nums = [-1,-2,3,4], k = 3
Output: [-1,3,4]
💡 Note: The 3 largest values are 4, 3, and -1. In original order: [-1,3,4]. Sum = -1 + 3 + 4 = 6.
Example 3 — Single Element
$ Input: nums = [3,4,3,3], k = 2
Output: [4,3]
💡 Note: We need any 2 elements with largest sum. The largest value 4 and any 3 will do. Taking indices [1,2] gives us [4,3].

Constraints

  • 1 ≤ nums.length ≤ 1000
  • 1 ≤ k ≤ nums.length
  • -105 ≤ nums[i] ≤ 105

Visualization

Tap to expand
Find Subsequence of Length K With Largest Sum INPUT Array: nums 0 1 2 3 2 1 3 1 nums = [2, 1, 3, 1] k = 2 (Find k elements with max sum) Goal: Select 2 elements maintaining original order with maximum sum ALGORITHM STEPS 1 Pair values with indices [(2,0), (1,1), (3,2), (1,3)] 2 Sort by value (descending) [(3,2), (2,0), (1,1), (1,3)] 3 Take top k=2 elements Selected: (3,2), (2,0) 4 Sort by index (original order) (2,0) comes before (3,2) Top k by value: 3 2 Sum = 3 + 2 = 5 (max) FINAL RESULT Output Subsequence (preserving original order) 2 idx: 0 3 idx: 2 Output: [2, 3] OK - Verified! Sum = 2 + 3 = 5 Length = 2 = k Order preserved: 0 then 2 Key Insight: The optimal approach is O(n log n): First sort elements by value to find the k largest, then sort those k elements by their original indices to maintain subsequence order. This avoids generating all possible subsequences (exponential) while guaranteeing the maximum sum with preserved ordering. TutorialsPoint - Find Subsequence of Length K With the Largest Sum | Optimal Solution
Asked in
Google 15 Amazon 12 Microsoft 8
23.5K Views
Medium Frequency
~15 min Avg. Time
850 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