Find Subsequence of Length K With the Largest Sum Problem
#2099
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2099.
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.
Example 1:
Input: nums = [2,1,3,3], k = 2
Output: [3,3]
Explanation:
The subsequence has the largest sum of 3 + 3 = 6.
Example 2:
Input: nums = [-1,-2,3,4], k = 3
Output: [-1,3,4]
Explanation:
The subsequence has the largest sum of -1 + 3 + 4 = 6.
Example 3:
Input: nums = [3,4,3,3], k = 2
Output: [3,4]
Explanation:
The subsequence has the largest sum of 3 + 4 = 7.
Another possible subsequence is [4, 3].
Constraints:
1 <= nums.length <= 1000-10^5 <= nums[i] <= 10^51 <= k <= nums.length
Solution
Approach: Sorting
Sort the indices 0..n-1 by their values in nums. The last k indices in that order point at the k largest values. Sort those k indices again, this time by position, so the values come out in their original order, and read nums at them.
Complexity: O(n log n) time, O(n) extra space for the index array.
class Solution:
def maxSubsequence(self, nums: List[int], k: int) -> List[int]:
idx = sorted(range(len(nums)), key=lambda i: nums[i])[-k:]
return [nums[i] for i in sorted(idx)]