Problem Description
You are given an integer array nums and a positive integer k. A subsequence is an array derived from nums by deleting some or no elements while keeping the order of the remaining ones. The K-Sum of the array is defined as the kth largest subsequence sum (the empty subsequence sum is 0). Return the K-Sum of the array.
Key Insights
- The largest subsequence sum is obtained by summing all positive numbers.
- Negative numbers, when included in a subsequence, reduce the overall sum. We can view each negative number as a “penalty” with magnitude = |negative value|.
- By computing posSum as the sum of all positive numbers, any subsequence sum can be written as: posSum minus the total penalty contributed by the negatives selected.
- The problem reduces to generating the k smallest possible penalty sums from the list of absolute values of negative numbers.
- A best-first search (using a min-heap) can be used to generate these penalty sums in increasing order without enumerating all (up to 2^(# of negatives)) possibilities.
Space and Time Complexity
Time Complexity: O(n log n + k log k)
• O(n log n) to partition and sort the negative numbers’ absolute values.
• O(k log k) in the worst-case for processing k elements from the heap.
Space Complexity: O(n + k)
• O(n) for storing the penalties.
• O(k) for the heap used in the best-first search.
Solution
- Calculate posSum as the sum of all positive numbers in nums.
- Collect the absolute values of all negative numbers (ignoring zeros since they do not change the sum) and sort them in ascending order.
- The goal is to determine penalty = (subset sum of these absolute values) such that the kth smallest penalty gives the kth largest subsequence sum (which equals posSum minus penalty).
- Use a min-heap (priority queue) to generate subset sums in increasing order. Initialize the heap with (currentPenalty = 0, currentIndex = 0).
- For each candidate (penalty, index) popped from the heap:
- This candidate represents a penalty sum associated with a subsequence choice of negatives.
- If index is less than the length of the penalty list, then generate two new candidates: • Include penaltyCandidates[index]: (penalty + penaltyCandidates[index], index + 1) • Exclude penaltyCandidates[index]: (penalty, index + 1)
- Use a visited set to avoid processing the same state more than once.
- When you pop the kth candidate (starting count from 1) from the heap, the answer is posSum minus this penalty.
- Return the result.