Skip to content

Commit 9a84e27

Browse files
committed
Add solution #2099
1 parent 772acd2 commit 9a84e27

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -272,6 +272,7 @@
272272
2053|[Kth Distinct String in an Array](./2053-kth-distinct-string-in-an-array.js)|Medium|
273273
2085|[Count Common Words With One Occurrence](./2085-count-common-words-with-one-occurrence.js)|Easy|
274274
2095|[Delete the Middle Node of a Linked List](./2095-delete-the-middle-node-of-a-linked-list.js)|Medium|
275+
2099|[Find Subsequence of Length K With the Largest Sum](./2099-find-subsequence-of-length-k-with-the-largest-sum.js)|Medium|
275276
2114|[Maximum Number of Words Found in Sentences](./2114-maximum-number-of-words-found-in-sentences.js)|Easy|
276277

277278
## License
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/**
2+
* 2099. Find Subsequence of Length K With the Largest Sum
3+
* https://leetcode.com/problems/find-subsequence-of-length-k-with-the-largest-sum/
4+
* Difficulty: Medium
5+
*
6+
* You are given an integer array nums and an integer k. You want to find a subsequence
7+
* of nums of length k that has the largest sum.
8+
*
9+
* Return any such subsequence as an integer array of length k.
10+
*
11+
* A subsequence is an array that can be derived from another array by deleting some or
12+
* no elements without changing the order of the remaining elements.
13+
*/
14+
15+
/**
16+
* @param {number[]} nums
17+
* @param {number} k
18+
* @return {number[]}
19+
*/
20+
var maxSubsequence = function(nums, k) {
21+
const map = new Map();
22+
nums.slice()
23+
.sort((a, b) => a - b)
24+
.slice(-k)
25+
.forEach(n => map.set(n, (map.get(n) || 0) + 1));
26+
27+
return nums.filter(n => {
28+
const isInSubsequence = map.get(n);
29+
30+
if (isInSubsequence) {
31+
map.set(n, map.get(n) - 1);
32+
}
33+
34+
return isInSubsequence;
35+
});
36+
};

0 commit comments

Comments
 (0)