The Find Subsequence of Length K With the Largest Sum problem involves selecting K
elements from an array such that their sum is maximized while maintaining their relative order.
This problem can be solved using a max-heap to track the largest elements and then sorting them by their original indices.
class Solution {
public int[] maxSubsequence(int[] nums, int k) {
PriorityQueue<int[]> maxHeap = new PriorityQueue<>(
(a, b) -> a[0] - b[0] // Min-heap based on values
);
// Step 1: Add elements to the heap and maintain size K
for (int i = 0; i < nums.length; i++) {
maxHeap.offer(new int[]{nums[i], i});
if (maxHeap.size() > k) {
maxHeap.poll(); // Remove the smallest element
}
}
// Step 2: Extract the top K elements
List<int[]> topK = new ArrayList<>(maxHeap);
// Step 3: Sort the elements by their original indices
topK.sort((a, b) -> a[1] - b[1]);
// Step 4: Extract the values
int[] result = new int[k];
for (int i = 0; i < k; i++) {
result[i] = topK.get(i)[0];
}
return result;
}
}
O(N log K)
โ Adding elements to the heap.O(K log K)
โ Sorting the top K elements by their indices.O(N log K)
.Input: nums = [2,1,3,3], k = 2
Output: [3,3]
Explanation:
- The top 2 elements are [3, 3].
- Sorting by their original indices gives [3, 3].
K
elements.