2025-06-28 Daily Challenge
Today I have done leetcode's June LeetCoding Challenge with cpp
.
June LeetCoding Challenge 28
Description
Find Subsequence of Length K With the Largest Sum
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] <= 105
1 <= k <= nums.length
Solution
class Solution {
public:
vector<int> maxSubsequence(vector<int>& nums, int k) {
vector<int> tmp(nums);
sort(tmp.begin(), tmp.end());
int len = nums.size();
multiset<int> candidates;
for(int i = 1; i <= k; ++i) {
candidates.insert(tmp[len - i]);
}
vector<int> answer;
for(auto n : nums) {
if(!candidates.count(n)) continue;
answer.push_back(n);
candidates.erase(candidates.find(n));
}
return answer;
}
};
// Accepted
// 49/49 cases passed (11 ms)
// Your runtime beats 7.68 % of cpp submissions
// Your memory usage beats 11.81 % of cpp submissions (14.4 MB)