Find Subsequence of Length K With the Largest Sum - Problem
You are given an integer array nums and an integer k. Your goal is to find a subsequence of exactly k elements from the array that has the largest possible sum.

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

What is a subsequence? A subsequence is derived from the original array by deleting some or no elements without changing the order of the remaining elements. For example, from [3, 6, 2, 7], valid subsequences include [3, 6, 7] and [6, 2].

Key constraint: You must maintain the original order of elements from the input array in your result.

Input & Output

example_1.py โ€” Basic Case
$ Input: nums = [2,1,3,3], k = 2
โ€บ Output: [3,3]
๐Ÿ’ก Note: The subsequence has the largest sum of 3 + 3 = 6. We select the two 3's while maintaining their original order (indices 2 and 3).
example_2.py โ€” Mixed Values
$ Input: nums = [-1,-2,3,4], k = 3
โ€บ Output: [-1,3,4]
๐Ÿ’ก Note: The subsequence has sum (-1) + 3 + 4 = 6. We skip -2 (the smallest) and take the 3 largest values while maintaining order.
example_3.py โ€” All Elements
$ Input: nums = [3,4,3,3], k = 4
โ€บ Output: [3,4,3,3]
๐Ÿ’ก Note: When k equals the array length, we must take all elements. The sum is 3 + 4 + 3 + 3 = 13.

Constraints

  • 1 โ‰ค nums.length โ‰ค 1000
  • 1 โ‰ค k โ‰ค nums.length
  • -105 โ‰ค nums[i] โ‰ค 105
  • The answer is guaranteed to be unique

Visualization

Tap to expand
๐Ÿ† Elite Team Selection ProcessOriginal LineupPlayer 2Player 1Player 3Player 3Selection Process๐Ÿ“‹ Min-Heap Trackingโ€ข Keep k best playersโ€ข Remove weakest when fullโ€ข Track original positionsCurrent Team (k=2)Player 3 (pos 2)Player 3 (pos 3)Final TeamPlayer 3Player 3Formation OrderMaintained! ๐ŸŽฏโšก Time: O(n log k) | ๐Ÿ’พ Space: O(k)
Understanding the Visualization
1
Scout Each Player
Examine each player's skill level as you move down the lineup
2
Maintain Top K
Keep track of the k best players seen so far, replacing weaker ones
3
Preserve Formation
Selected players maintain their original lineup positions
4
Final Team
Output the selected players in their formation order
Key Takeaway
๐ŸŽฏ Key Insight: Use a min-heap to efficiently track the k strongest players, then arrange them in formation order. This strategy balances selection efficiency with formation constraints!
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28 Apple 22
42.3K Views
Medium-High Frequency
~15 min Avg. Time
1.8K 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