Problem Description
Given an integer array nums and an integer k, find any subsequence of nums of length k that has the largest sum. The subsequence must keep the same relative order as in the original array.
Key Insights
- The problem asks for a subsequence, not a contiguous segment.
- We need to choose k elements from the array that maximize the sum.
- The relative order of the selected elements must be preserved.
- One effective approach is to select the top k elements by value, then sort these selected elements by their original indices to maintain order.
- Alternatively, a min-heap of size k can be maintained while traversing the array to achieve O(n log k) time.
Space and Time Complexity
Time Complexity: O(n log n) using sorting or O(n log k) using a min-heap
Space Complexity: O(n) to store index-value pairs or O(k) for the heap
Solution
The algorithm involves two main steps:
- Iterate over nums and record each element along with its original index.
- Select the k largest elements by value; if values are equal, the relative order (i.e., original index) will help in preserving the subsequence integrity.
- After selecting the k largest elements, sort them by their original indices to restore the order as it appears in nums.
- Return the values in this sorted order as the subsequence with the largest sum.
This approach leverages sorting (or a heap) to pick the largest values and then uses sorting again to maintain the original subsequence order.
Code Solutions
Below are the sample solutions in Python, JavaScript, C++, and Java.