1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| class Solution { public int[] maxSubsequence(int[] nums, int k) { Queue<int[]> queue = new PriorityQueue<>(Comparator.comparingInt(o -> o[0])); for (int i = 0; i < k; i++) { queue.offer(new int[]{nums[i], i}); } for (int i = k; i < nums.length; i++) { if (nums[i] > nums[queue.peek()[1]]) { queue.offer(new int[]{nums[i], i}); queue.poll(); } }
List<int[]> list = new ArrayList<>(queue.size()); while (!queue.isEmpty()) { list.add(queue.poll()); } list.sort(Comparator.comparingInt(o -> o[1]));
int[] res = new int[k]; for (int i = 0; i < k; i++) { res[i] = list.get(i)[0]; } return res; } }
|
References
2099. Find Subsequence of Length K With the Largest Sum