2204. Find Subsequence Of Length K With The Largest Sum¶
Difficulty: Easy
LeetCode Problem View on GitHub
2204. Find Subsequence of Length K With the Largest Sum
Easy
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-105 <= nums[i] <= 1051 <= k <= nums.length
Solution¶
class Solution {
static class custom_sort implements Comparator<Integer> {
@Override
public int compare(Integer first, Integer second) {
return Integer.compare(second, first);
}
}
public int[] maxSubsequence(int[] nums, int k) {
int n = nums.length;
PriorityQueue<Integer> pq = new PriorityQueue<>(new custom_sort());
for(int i = 0; i < n; i++)
pq.offer(nums[i]);
int res[] = new int[k];
int p = 0;
HashMap<Integer, Integer> map = new HashMap<>();
while(k > 0) {
int ele = pq.poll();
map.put(ele, map.getOrDefault(ele, 0) + 1);
k--;
}
for(int i = 0; i < n; i++) {
if(map.containsKey(nums[i])) {
res[p++] = nums[i];
map.put(nums[i] , map.getOrDefault(nums[i] , 0) - 1);
if(map.get(nums[i]) == 0)
map.remove(nums[i]);
}
}
return res;
}
}
Complexity Analysis¶
- Time Complexity:
O(?) - Space Complexity:
O(?)
Approach¶
Detailed explanation of the approach will be added here