Thanksgiving Sale: Use Coupon Code THANKS25 to Get Extra 25% Off.
09DAYS
:
09HOURS
:
37MINUTES
:
10SECONDS
Leetcode Problem 2386. Find the K-Sum of an Array
2386. Find the K-Sum of an Array
Leetcode Solutions
Priority Queue Approach for K-Sum Problem
Calculate the initial maximum sum by summing all positive numbers in the array.
Convert all negative numbers to their absolute values and sort the array.
Initialize a priority queue and insert a pair containing the initial maximum sum minus the smallest number and the index 0.
Repeat the following steps until k-1 smallest sums are found:
a. Extract the smallest sum from the priority queue.
b. Insert two new sums into the priority queue: one including the next number and one excluding it.
The k-th largest sum is the initial maximum sum minus the k-1 smallest sum found.