Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Logic:
- 1. Count the differences between each nums1[i] and nums2[i] and store them into an int[100_001], as nums is between 0 and 100_000.
- 2. Let's look at the example of [1,4,10,12], [4,8,6,7]. k1= 1, k2 =1
- Looking at the pairs of abs diff we have 3,4,4,5.
- So a total of 16 diff points with k = 2.
- As we observe, if we use the k operations on the first pair, we can decrease 3 to 1.
- but this would only help with 3^2 (9) -> 1. So we decrease the totam sum diff by 8.
- However, if we operate on the diff of 5, this would have much more impact.
- 5 - 1 => (4^2)25 - 16 . so we save 9 points by using 1 k
- 5 - 2 => (3^2) 25 - 9. So we save 16 points.
- 3. As we can see, we need to operate on the highest diff, lowering them.
- 4. As we have counted them on step #1, we would have an array like this
- [0,0,0,1,2,1] : 1 diff of 3, 2 of 4 and 1 of 5.
- 5. While k is > 0 (k1 + k2), start from the back (highest) and decrease it one group at a time.
- So make all 5 diffs into 4 diff, only if their cardinal is <= k. If it's greater than k, we can only
- lower k diff to diff -1.
- So [0,0,0,1,2,1] and k = 2 => [0,0,0,1,3,0] and k =1
- We have 3 diff of 4 and just k =1 so we can turn one 4 into a 3.
- => [0,0,0,2,2,0]. Thus. the diff becomes 2 of 3 and 2 of 4.
- */
- class Solution {
- public:
- long long minSumSquareDiff(vector<int>& nums1, vector<int>& nums2, int k1, int k2) {
- int n = nums1.size(),M=INT_MIN;
- vector<int> diff(n);
- for(int i = 0; i<n; ++i) {
- diff[i] = abs(nums1[i] - nums2[i]); //This line is storing difference in normal array
- M=max(diff[i],M); //finding the maximum difference to make the actual array.
- }
- vector<int> bucket(M+1);
- for(int i = 0 ; i<n; ++i) {
- bucket[diff[i]]++; //Here count of all difference is stored at index difference.
- }
- int k = k1 + k2;
- for(int i = M; i > 0 && k>0; --i) {
- if(bucket[i] > 0) {
- int minus = min(bucket[i], k);
- bucket[i] -= minus;
- bucket[i-1] += minus;
- k -= minus;
- }
- }
- long long ans = 0;
- for(long long i = M; i > 0; --i) {
- ans += bucket[i]*i*i;
- }
- return ans;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement