Skip to content

Commit 4205115

Browse files
committed
Add solution #2386
1 parent 7b7cd59 commit 4205115

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2164,6 +2164,7 @@
21642164
2383|[Minimum Hours of Training to Win a Competition](./solutions/2383-minimum-hours-of-training-to-win-a-competition.js)|Easy|
21652165
2384|[Largest Palindromic Number](./solutions/2384-largest-palindromic-number.js)|Medium|
21662166
2385|[Amount of Time for Binary Tree to Be Infected](./solutions/2385-amount-of-time-for-binary-tree-to-be-infected.js)|Medium|
2167+
2386|[Find the K-Sum of an Array](./solutions/2386-find-the-k-sum-of-an-array.js)|Hard|
21672168
2387|[Median of a Row Wise Sorted Matrix](./solutions/2387-median-of-a-row-wise-sorted-matrix.js)|Medium|
21682169
2389|[Longest Subsequence With Limited Sum](./solutions/2389-longest-subsequence-with-limited-sum.js)|Easy|
21692170
2390|[Removing Stars From a String](./solutions/2390-removing-stars-from-a-string.js)|Medium|
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/**
2+
* 2386. Find the K-Sum of an Array
3+
* https://leetcode.com/problems/find-the-k-sum-of-an-array/
4+
* Difficulty: Hard
5+
*
6+
* You are given an integer array nums and a positive integer k. You can choose any subsequence
7+
* of the array and sum all of its elements together.
8+
*
9+
* We define the K-Sum of the array as the kth largest subsequence sum that can be obtained
10+
* (not necessarily distinct).
11+
*
12+
* Return the K-Sum of the array.
13+
*
14+
* A subsequence is an array that can be derived from another array by deleting some or no elements
15+
* without changing the order of the remaining elements.
16+
*
17+
* Note that the empty subsequence is considered to have a sum of 0.
18+
*/
19+
20+
/**
21+
* @param {number[]} nums
22+
* @param {number} k
23+
* @return {number}
24+
*/
25+
var kSum = function(nums, k) {
26+
const maxSum = nums.reduce((sum, num) => sum + Math.max(0, num), 0);
27+
const absoluteNums = nums.map(num => Math.abs(num)).sort((a, b) => a - b);
28+
const maxHeap = new PriorityQueue((a, b) => a[0] - b[0]);
29+
maxHeap.enqueue([-maxSum + absoluteNums[0], 0]);
30+
let nextSum = -maxSum;
31+
32+
for (let iteration = 0; iteration < k - 1; iteration++) {
33+
[nextSum, i] = maxHeap.dequeue();
34+
35+
if (i + 1 < absoluteNums.length) {
36+
maxHeap.enqueue([nextSum - absoluteNums[i] + absoluteNums[i + 1], i + 1]);
37+
maxHeap.enqueue([nextSum + absoluteNums[i + 1], i + 1]);
38+
}
39+
}
40+
41+
return -nextSum;
42+
};

0 commit comments

Comments
 (0)