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 SumInput: nums = [2,1,3,1], k = 22131index 0index 1index 2index 3Select 2 largest values: 3 (index 2) and 2 (index 0)Maintain original order: indices [0,2] → values [2,3]23Output: [2,3] with sum = 5
Understanding the Visualization
1
Input
Array nums=[2,1,3,1] and k=2
2
Process
Find 2 largest values: 3 and 2
3
Output
Return [2,3] maintaining original order
Key Takeaway
🎯 Key Insight: We must find k largest values but preserve their relative positions from the original array
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