Physical Address

304 North Cardinal St.
Dorchester Center, MA 02124

Find the K-Sum of an Array LeetCode Solution

Problem – Find the K-Sum of an Array

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.

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.length
  • 1 <= n <= 105
  • -109 <= nums[i] <= 109
  • 1 <= k <= min(2000, 2n)

Find the K-Sum of an Array LeetCode Solution in C++

class Solution {
public:
    long long kSum(vector<int>& nums, int k) {
        int n=nums.size();
        vector<long long>ans;
        priority_queue<pair<long long,long long>>pq;
        long long sum=0;
        for(int i=0;i<n;i++)
        {
            if(nums[i]>0)
            {
                sum+=nums[i];
            }
            nums[i]=abs(nums[i]);
        }
        sort(nums.begin(),nums.end());
        pq.push({sum-nums[0],0});
        ans.push_back(sum);
        while(ans.size()<k)
        {
            auto [val,index]=pq.top();
            pq.pop();
            ans.push_back(val);
            if(index+1<n)
            {
                pq.push({val+nums[index]-nums[index+1],index+1});
                pq.push({val-nums[index+1],index+1});
            }
        }
        return ans[k-1];
    }
};

Find the K-Sum of an Array LeetCode Solution in Java

class Solution {
    public long kSum(int[] nums, int k) {
        long sum = 0;
        Queue<Pair<Long, Integer>> pq = new PriorityQueue<>((a, b) -> Long.compare(b.getKey(), a.getKey()));
        for (int i = 0; i < nums.length; i++) {
            sum = sum + Math.max(0, nums[i]);
        }
        for (int i = 0; i < nums.length; i++) {
            nums[i] = Math.abs(nums[i]);
        }
        Arrays.sort(nums);
        long result = sum;
        pq.offer(new Pair<>(sum - nums[0], 0));
        while (--k > 0) {
            Pair<Long, Integer> pair = pq.poll();
            result = pair.getKey();
            int index = pair.getValue();
            if (index < nums.length - 1) {
                pq.offer(new Pair<>(result + nums[index] - nums[index + 1], index + 1));
                pq.offer(new Pair<>(result - nums[index + 1], index + 1));
            }
        }        
        return result;
    }
}

Find the K-Sum of an Array LeetCode Solution in Python

import heapq


class Solution:
    def kSum(self, nums: List[int], k: int) -> int:
        heap = []
        
        # get maximal subsequence sum
        max_subset = sum(n for n in nums if n > 0)
        removal_candidates = list(sorted(nums, key=lambda x: abs(x)))
        
        # keep max_heap of next largest subset sum
        heap.append((-max_subset, -1))
        ans = max_subset

        # pop k times
        for _ in range(k):
            candidate, idx = heapq.heappop(heap)
            ans = min(ans, -candidate)
            
            # while we still have items to remove, create new candidate subseq sum
            if idx + 1 < len(removal_candidates):
                # remove candidate element and keep track of last index
                heapq.heappush(heap, (candidate + abs(removal_candidates[idx + 1]), idx + 1))
                # if we need to readd elements previously removed
                if idx >= 0:
                    heapq.heappush(heap, (candidate - abs(removal_candidates[idx]) + abs(removal_candidates[idx + 1]), idx + 1))

        return ans
Find the K-Sum of an Array LeetCode Solution Review:

In our experience, we suggest you solve this Find the K-Sum of an Array LeetCode Solution and gain some new skills from Professionals completely free and we assure you will be worth it.

If you are stuck anywhere between any coding problem, just visit Queslers to get the Find the K-Sum of an Array LeetCode Solution

Find on LeetCode

Conclusion:

I hope this Find the K-Sum of an Array LeetCode Solution would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.

This Problem is intended for audiences of all experiences who are interested in learning about Data Science in a business context; there are no prerequisites.

Keep Learning!

More Coding Solutions >>

LeetCode Solutions

Hacker Rank Solutions

CodeChef Solutions

Leave a Reply

Your email address will not be published. Required fields are marked *