|
| 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