Find the K-Sum of an Array - Problem
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 kth 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: The empty subsequence is considered to have a sum of 0.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [2,4,-2], k = 5
›
Output:
2
💡 Note:
All subsequence sums in descending order: [6,4,4,2,2,0,-2,-2], so the 5th largest is 2
Example 2 — All Positive
$
Input:
nums = [1,1,1], k = 3
›
Output:
2
💡 Note:
Subsequence sums: [3,2,2,2,1,1,1,0], so the 3rd largest is 2
Example 3 — Mixed Numbers
$
Input:
nums = [5,-2,1], k = 3
›
Output:
1
💡 Note:
Subsequence sums sorted: [6,4,3,1,1,-1,-2,-2], the 3rd largest is 1
Constraints
- 1 ≤ nums.length ≤ 105
- -105 ≤ nums[i] ≤ 105
- 1 ≤ k ≤ min(2000, 2nums.length)
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array [2,4,-2] and k=5
2
Generate Sums
All subsequence sums: [6,4,4,2,2,0,-2,-2]
3
Find K-th
5th largest sum = 2
Key Takeaway
🎯 Key Insight: Transform the problem using positive/negative separation and generate sums efficiently with a priority queue
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code