Skip to content

Commit 5f59191

Browse files
authored
Create find-subsequence-of-length-k-with-the-largest-sum.cpp
1 parent 15d7bfe commit 5f59191

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
// Time: O(n)
2+
// Space: O(n)
3+
4+
class Solution {
5+
public:
6+
vector<int> maxSubsequence(vector<int>& nums, int k) {
7+
vector<int> partition(begin(nums), end(nums));
8+
nth_element(begin(partition), begin(partition) + k - 1, end(partition), greater<int>());
9+
int cnt = count(begin(partition), begin(partition) + k, partition[k - 1]);
10+
vector<int> result;
11+
for (int i = 0; i < size(nums); ++i) {
12+
if (nums[i] > partition[k - 1] || (nums[i] == partition[k - 1] && --cnt >= 0)) {
13+
result.emplace_back(nums[i]);
14+
}
15+
}
16+
return result;
17+
}
18+
};

0 commit comments

Comments
 (0)