- 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
- 55 lines of C++ from the credited upstream file 2333.cpp.
- The implementation visibly relies on sequence storage, hash lookup, work queue.
- 5 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 minSumSquareDiff(vector<int>& nums1, vector<int>& nums2, int k1,4 int k2) {5 const vector<int> diff = getDiff(nums1, nums2);6 int k = k1 + k2;7 if (accumulate(diff.begin(), diff.end(), 0L) <= k)8 return 0;9 10 unordered_map<int, int> count;11 priority_queue<pair<int, int>> maxHeap; 12 13 for (const int d : diff)14 if (d != 0)15 ++count[d];16 17 for (const auto& [num, freq] : count)18 maxHeap.emplace(num, freq);19 20 while (k > 0) {21 const auto [maxNum, maxNumFreq] = maxHeap.top();22 maxHeap.pop();23 24 const int numDecreased = min(k, maxNumFreq);25 k -= numDecreased;26 if (maxNumFreq > numDecreased)27 maxHeap.emplace(maxNum, maxNumFreq - numDecreased);28 if (!maxHeap.empty() && maxHeap.top().first + 1 == maxNum) {29 const auto [secondMaxNum, secondMaxNumFreq] = maxHeap.top();30 maxHeap.pop();31 maxHeap.emplace(secondMaxNum, secondMaxNumFreq + numDecreased);32 } else if (maxNum > 1) {33 maxHeap.emplace(maxNum - 1, numDecreased);34 }35 }36 37 long ans = 0;38 while (!maxHeap.empty()) {39 const auto [num, freq] = maxHeap.top();40 maxHeap.pop();41 ans += static_cast<long>(num) * num * freq;42 }43 44 return ans;45 }46 47 private:48 vector<int> getDiff(const vector<int>& nums1, const vector<int>& nums2) {49 vector<int> diff;50 for (int i = 0; i < nums1.size(); ++i)51 diff.push_back(abs(nums1[i] - nums2[i]));52 return diff;53 }54};55