[translate by ChatGPT] I actually thought of the solution early on, but at first I didn’t notice that the problem requires choosing k elements. I initially thought it only required finding the two largest values.

Later I realized that I could implement it using a min heap. This also made me feel that I should review how to use a min heap again. The usage of priority_queue is actually quite simple: just use top() to get the element, and then push() / pop().

Later I realized that I didn’t properly handle the case where nums1 values are the same. I spent some extra time thinking about how to deal with that, and also spent some time implementing and verifying it. But overall this problem went quite smoothly.

Code

class Solution {
public:
    vector<long long> findMaxSum(vector<int>& nums1, vector<int>& nums2, int k) {
        int n = nums1.size();
        vector<pair<int,int>> idx1;
        for(int i = 0 ; i < n ; ++i) {
            idx1.push_back({nums1[i], i});
        }
        sort(idx1.begin(), idx1.end());
        vector<long long> ans(n, 0);
        long long max1 = 0, max2 = 0;
        priority_queue<int, vector<int>, greater<int>> minHeap;
        long long curSum = 0, prevSum = 0;
        int maxNum = idx1[0].first;
        for(int i = 0 ; i < k ; ++i) {
            minHeap.push(0);
        }
        for(int i = 0 ; i < n ; ++i) {
            int cur = nums2[idx1[i].second];
            if(maxNum < idx1[i].first) {
                prevSum = curSum;
                maxNum = idx1[i].first;
            }
            ans[idx1[i].second] = prevSum;
            if (cur > minHeap.top()) {
                curSum -= minHeap.top();
                minHeap.pop();
                minHeap.push(cur);
                curSum += cur;
            }
        }
        return ans;
    }
};