Leetcode 2099. Find Subsequence of Length K With the Largest Sum
Given an integer array nums
and an integer k
, return the subsequence of nums
(not necessarily contiguous) of length k
that has the largest sum. If there are multiple answers, return any of them.
k
be larger than the length of the nums
array?
k
will always be less than or equal to the length of the nums
array.nums
contain negative numbers?
nums
can contain negative numbers.(element, index)
from the nums
array.k
elements.nums
.#include <vector>
#include <algorithm>
#include <iostream>
std::vector<int> maxSubsequence(std::vector<int>& nums, int k) {
// Step 1: Pair each element with its index
std::vector<std::pair<int, int>> nums_with_indices;
for (int i = 0; i < nums.size(); ++i) {
nums_with_indices.push_back({nums[i], i});
}
// Step 2: Sort the pairs by their values in descending order
std::sort(nums_with_indices.begin(), nums_with_indices.end(),
[](const std::pair<int, int>& a, const std::pair<int, int>& b) {
return a.first > b.first;
}
);
// Step 3: Extract the indices of the top k elements
std::vector<int> indices;
for (int i = 0; i < k; ++i) {
indices.push_back(nums_with_indices[i].second);
}
// Step 4: Sort the indices to maintain the original order
std::sort(indices.begin(), indices.end());
// Step 5: Extract the elements using the sorted indices
std::vector<int> result;
for (int index : indices) {
result.push_back(nums[index]);
}
return result;
}
// Example usage
int main() {
std::vector<int> nums = {3, 4, 3, 3};
int k = 2;
std::vector<int> result = maxSubsequence(nums, k);
// Output the result
for (int num : result) {
std::cout << num << " ";
}
return 0;
}
n
is the number of elements in nums
.k
indices takes O(k log k).Overall, the dominant factor is the sorting step, so the time complexity is O(n log n).
This approach ensures that we correctly find the subsequence of length k
with the largest sum while maintaining the order of elements as in the original nums
array.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?