Find the K-Sum of an Array Problem
Description
LeetCode Problem 2386.
You are given an integer array nums and a positive integer k. You can choose any subsequence of the array and sum all of its elements together.
We define the K-Sum of the array as the k^th largest subsequence sum that can be obtained (not necessarily distinct).
Return the K-Sum of the array.
A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.
Note that the empty subsequence is considered to have a sum of 0.
Example 1:
Input: nums = [2,4,-2], k = 5
Output: 2
Explanation: All the possible subsequence sums that we can obtain are the following sorted in decreasing order:
6, 4, 4, 2, 2, 0, 0, -2.
The 5-Sum of the array is 2.
Example 2:
Input: nums = [1,-2,3,4,-10,12], k = 16
Output: 10
Explanation: The 16-Sum of the array is 10.
Constraints:
n == nums.length1 <= n <= 10^5-10^9 <= nums[i] <= 10^91 <= k <= min(2000, 2^n)
Solution
Approach: Min-Heap
The largest subsequence sum mx is the sum of all positive numbers. Every other subsequence sum equals mx minus a non-negative cost: skipping a positive number costs its value, and taking a negative number costs its absolute value. So the k-th largest sum is mx minus the k-th smallest cost, where costs are sums of subsets of the absolute values.
Sort the absolute values and enumerate subset sums in increasing order with a min-heap of (sum, i), where i is the next index that may be used. Pop the smallest entry and push two follow-ups: add a[i], or replace the last used element a[i-1] by a[i]. Because the values are sorted, this visits every subset sum once, in order. After k - 1 pops, the smallest entry in the heap is the k-th smallest cost.
Complexity: time O(n log n + k log k), space O(n + k), where n is the length of nums.
from heapq import heappop, heappush
class Solution:
def kSum(self, nums: List[int], k: int) -> int:
mx = 0
for i, x in enumerate(nums):
if x > 0:
mx += x
else:
nums[i] = -x
nums.sort()
h = [(0, 0)]
for _ in range(k - 1):
s, i = heappop(h)
if i < len(nums):
heappush(h, (s + nums[i], i + 1))
if i:
heappush(h, (s + nums[i] - nums[i - 1], i + 1))
return mx - h[0][0]