Problem solution · C++

Find the K-Sum of an Array

Find the K-Sum of an Array: a C++ solution using heap or priority queue. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Heap or priority queue
Source
walkccc LeetCode Solutions
Length
42 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Heap or priority queue

For Find the K-Sum of an Array, the implementation repeatedly takes the currently best candidate from a heap while inserting newly available choices.

  1. Define the priority key and whether the smallest or largest item should lead.
  2. Push each candidate when it becomes eligible.
  3. Discard stale entries when necessary and process the best live candidate.

Code notes

  • 42 lines of C++ from the credited upstream file 2386.cpp.
  • The implementation visibly relies on sequence storage, work queue.
  • 3 loop blocks detected.

Complexity

Count heap pushes and pops; each normally contributes a logarithmic factor in the heap size.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeFind the K-Sum of an Array · C++C++
Use this to learn the idea, then write your own version.
class Solution { public:  long long kSum(vector<int>& nums, int k) {    const long long maxSum = getMaxSum(nums);    const vector<int> absNums = getAbsNums(nums);    long long ans = maxSum;    // (the next maximum sum, the next index i)    using P = pair<long long, int>;    priority_queue<P> maxHeap;    maxHeap.emplace(maxSum - absNums[0], 0);     for (int j = 0; j < k - 1; ++j) {      const auto [nextMaxSum, i] = maxHeap.top();      maxHeap.pop();      ans = nextMaxSum;      if (i + 1 < absNums.size()) {        maxHeap.emplace(nextMaxSum - absNums[i + 1], i + 1);        maxHeap.emplace(nextMaxSum - absNums[i + 1] + absNums[i], i + 1);      }    }     return ans;  }  private:  long long getMaxSum(const vector<int>& nums) {    long long maxSum = 0;    for (const int num : nums)      if (num > 0)        maxSum += num;    return maxSum;  }   vector<int> getAbsNums(const vector<int>& nums) {    vector<int> absNums;    for (const int num : nums)      absNums.push_back(abs(num));    ranges::sort(absNums);    return absNums;  }}; 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗