- Define the priority key and whether the smallest or largest item should lead.
- Push each candidate when it becomes eligible.
- 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.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 long long kSum(vector<int>& nums, int k) {4 const long long maxSum = getMaxSum(nums);5 const vector<int> absNums = getAbsNums(nums);6 long long ans = maxSum;7 8 using P = pair<long long, int>;9 priority_queue<P> maxHeap;10 maxHeap.emplace(maxSum - absNums[0], 0);11 12 for (int j = 0; j < k - 1; ++j) {13 const auto [nextMaxSum, i] = maxHeap.top();14 maxHeap.pop();15 ans = nextMaxSum;16 if (i + 1 < absNums.size()) {17 maxHeap.emplace(nextMaxSum - absNums[i + 1], i + 1);18 maxHeap.emplace(nextMaxSum - absNums[i + 1] + absNums[i], i + 1);19 }20 }21 22 return ans;23 }24 25 private:26 long long getMaxSum(const vector<int>& nums) {27 long long maxSum = 0;28 for (const int num : nums)29 if (num > 0)30 maxSum += num;31 return maxSum;32 }33 34 vector<int> getAbsNums(const vector<int>& nums) {35 vector<int> absNums;36 for (const int num : nums)37 absNums.push_back(abs(num));38 ranges::sort(absNums);39 return absNums;40 }41};42