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: 4
💡 Note: Subsequence sums sorted: [6,5,4,3,1,0,-1,-2], the 3rd largest is 4

Constraints

  • 1 ≤ nums.length ≤ 105
  • -105 ≤ nums[i] ≤ 105
  • 1 ≤ k ≤ min(2000, 2nums.length)

Visualization

Tap to expand
Find the K-Sum of an Array INPUT Array nums: 2 idx 0 4 idx 1 -2 idx 2 k = 5 All Subsequence Sums: [] = 0 [2] = 2 [4] = 4 [-2] = -2 [2,4] = 6 [2,-2] = 0 [4,-2] = 2 [2,4,-2] = 4 Sorted: 6,4,4,2,2,0,0,-2 (descending order) 5th largest = 2 ALGORITHM STEPS 1 Calculate Max Sum Sum all positives: 2+4=6 2 Convert to Abs Values abs(nums) = [2,4,2] 3 Sort Absolute Values sorted = [2,2,4] 4 Use Min-Heap Track k smallest subtractions Min-Heap Process: Pop 1: sum=6, sub=0 --> 6 Pop 2: sum=6, sub=2 --> 4 Pop 3: sum=6, sub=2 --> 4 Pop 4: sum=6, sub=4 --> 2 Pop 5: sum=6, sub=4 --> 2 FINAL RESULT K-Sum (5th largest): 2 Verification: Rank 1: 6 = [2,4] Rank 2: 4 = [4] or [2,4,-2] Rank 3: 4 = [4] or [2,4,-2] Rank 4: 2 = [2] or [4,-2] Rank 5: 2 = [2] or [4,-2] OK - Answer confirmed! Output: 2 Key Insight: Instead of generating all 2^n subsequences, we find max sum (sum of positives) and use a min-heap to find the k smallest "subtractions" from max. Converting to absolute values lets us treat this as finding k smallest subset sums, which can be done efficiently in O(n log n + k log k) using a priority queue. TutorialsPoint - Find the K-Sum of an Array | Optimal Solution
Asked in
Google 25 Amazon 18 Microsoft 15 Meta 12
23.4K Views
Medium Frequency
~35 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen