Basically, we just want to find the k largest values of nums and return them in their original order.
We can do this by:
pairing each value in
numswith its respective index,pairedNumssort the array
pairedNumsand extract theklargest valuesthen, simply extract the indices and place the respective values back into an
ansarray
code link to code
class Solution {
public:
vector<int> maxSubsequence(vector<int>& nums, int k) {
vector<pair<int, int>> pairedNums;
for (int i = 0; i < nums.size(); ++i) {
pairedNums.push_back({nums[i], i});
}
sort(pairedNums.begin(), pairedNums.end(), greater());
vector<int> indices;
vector<int> ans;
for (int i = 0; i < k; ++i) {
indices.push_back(pairedNums[i].second);
}
sort(indices.begin(), indices.end());
for (int i = 0; i < indices.size(); ++i) {
ans.push_back(nums[indices[i]]);
}
return ans;
}
};complexity link to complexity
- Time:
O(n log(n))wherenis the size ofnums- Space:
O(n)
time taken link to time taken
- 7 minutes and 49 seconds