3774. Absolute Difference Between Maximum and Minimum K Elements
You are given an integer array nums and an integer k.
Find the absolute difference between:
- the sum of the
k largest elements in the array; and
- the sum of the
k smallest elements in the array.
Return an integer denoting this difference.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| class Solution { public: int absDifference(vector<int>& nums, int k) { priority_queue<int,vector<int>,greater<>> hi; priority_queue<int> lo; for(auto& n : nums) { hi.push(n); lo.push(n); if(hi.size() > k) hi.pop(); if(lo.size() > k) lo.pop(); } int res = 0; while(hi.size()) { res += hi.top(); hi.pop(); } while(lo.size()) { res -= lo.top(); lo.pop(); } return res; } };
|