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
Similar Questions:
- Kth Largest Element in an Array (Medium)
- Maximize Sum Of Array After K Negations (Easy)
- Sort Integers by The Number of 1 Bits (Easy)
// OJ: https://leetcode.com/problems/find-subsequence-of-length-k-with-the-largest-sum/
// Author: github.com/lzl124631x
// Time: O(NlogN)
// Space: O(N)
class Solution {
public:
vector<int> maxSubsequence(vector<int>& A, int k) {
vector<int> id(A.size());
iota(begin(id), end(id), 0); // Index array 0, 1, 2, ...
sort(begin(id), end(id), [&](int a, int b) { return A[a] > A[b]; }); // Sort the indexes in descending order of their corresponding values in `A`
id.resize(k); // Only keep the first `k` indexes with the greatest `A` values
sort(begin(id), end(id)); // Sort indexes in ascending order
vector<int> ans;
for (int i : id) ans.push_back(A[i]);
return ans;
}
};
// OJ: https://leetcode.com/problems/find-subsequence-of-length-k-with-the-largest-sum/
// Author: github.com/lzl124631x
// Time: O(N + KlogK) on average, O(N^2 + KlogK) in the worst case
// Space: O(N)
class Solution {
public:
vector<int> maxSubsequence(vector<int>& A, int k) {
vector<int> id(A.size());
iota(begin(id), end(id), 0);
nth_element(begin(id), begin(id) + k, end(id), [&](int a, int b) { return A[a] > A[b]; });
id.resize(k);
sort(begin(id), end(id));
vector<int> ans;
for (int i : id) ans.push_back(A[i]);
return ans;
}
};
// OJ: https://leetcode.com/problems/find-subsequence-of-length-k-with-the-largest-sum/
// Author: github.com/lzl124631x
// Time: O(N) on average, O(N^2) in the worst case
// Space: O(N)
class Solution {
public:
vector<int> maxSubsequence(vector<int>& A, int k) {
if (k == A.size()) return A;
vector<int> v(begin(A), end(A)), ans;
nth_element(begin(v), begin(v) + k - 1, end(v), greater<>());
int cnt = count(begin(v), begin(v) + k, v[k - 1]);
for (int i = 0; i < A.size(); ++i) {
if (A[i] > v[k - 1] || (A[i] == v[k - 1] && --cnt >= 0)) ans.push_back(A[i]);
}
return ans;
}
};