- 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
- 34 lines of C++ from the credited upstream file 3478.cpp.
- The implementation visibly relies on sequence storage, work queue.
- 2 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 vector<long long> findMaxSum(vector<int>& nums1, vector<int>& nums2, int k) {4 const int n = nums1.size();5 vector<long long> ans(n);6 vector<pair<int, int>> numAndIndexes;7 priority_queue<long long, vector<long long>, greater<long long>> minHeap;8 9 for (int i = 0; i < n; i++)10 numAndIndexes.emplace_back(nums1[i], i);11 12 ranges::sort(numAndIndexes);13 14 const int firstIndex = numAndIndexes[0].second;15 minHeap.push(nums2[firstIndex]);16 long sum = nums2[firstIndex];17 18 for (int i = 1; i < n; ++i) {19 const auto& [currNum, currIndex] = numAndIndexes[i];20 const auto& [prevNum, prevIndex] = numAndIndexes[i - 1];21 if (currNum == prevNum)22 ans[currIndex] = ans[prevIndex];23 else24 ans[currIndex] = sum;25 minHeap.push(nums2[currIndex]);26 sum += nums2[currIndex];27 if (minHeap.size() == k + 1)28 sum -= minHeap.top(), minHeap.pop();29 }30 31 return ans;32 }33};34