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^5
1 <= k <= nums.length
Can you write a function that efficiently finds a subsequence of length k
with the largest sum?
A brute force solution would involve generating all possible subsequences of length k
from the input array nums
, calculating the sum of each subsequence, and then selecting the subsequence with the largest sum. This approach has a time complexity that makes it impractical for larger input sizes.
k
from nums
.A more efficient approach involves these steps:
k
largest elements.k
largest elements based on their original indices to maintain the original order.nums
.k
pairs from the sorted array.k
pairs based on their original indices.k
is equal to the length of nums
, return the original nums
array.nums
contains duplicate values, the algorithm should correctly select k
elements regardless of their position.def largest_subsequence(nums, k):
# Create a list of (value, index) pairs
indexed_nums = [(val, i) for i, val in enumerate(nums)]
# Sort by value in descending order
indexed_nums.sort(key=lambda x: x[0], reverse=True)
# Select the top k elements
top_k = indexed_nums[:k]
# Sort by index to maintain original order
top_k.sort(key=lambda x: x[1])
# Extract the values
result = [val for val, _ in top_k]
return result