Advertisement
imashutosh51

Minimum Sum of Squared Difference

Oct 8th, 2022 (edited)
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.34 KB | None | 0 0
  1. /*
  2. Logic:
  3.  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.
  4.  2. Let's look at the example of [1,4,10,12], [4,8,6,7]. k1= 1, k2 =1
  5.      Looking at the pairs of abs diff we have 3,4,4,5.
  6.      So a total of 16 diff points with k = 2.
  7.      As we observe, if we use the k operations on the first pair, we can decrease 3 to 1.
  8.      but this would only help with 3^2 (9) -> 1. So we decrease the totam sum diff by 8.
  9.      However, if we operate on the diff of 5, this would have much more impact.
  10.      5 - 1 => (4^2)25 - 16 . so we save 9 points by using 1 k
  11.      5 - 2 => (3^2) 25 - 9. So we save 16 points.
  12.  3. As we can see, we need to operate on the highest diff, lowering them.
  13.  4. As we have counted them on step #1, we would have an array like this
  14.    [0,0,0,1,2,1] : 1 diff of 3, 2 of 4 and 1 of 5.
  15.  5. While k is > 0 (k1 + k2), start from the back (highest) and decrease it one group at a time.
  16.    So make all 5 diffs into 4 diff, only if their cardinal is <= k. If it's greater than k, we can only
  17.    lower k diff to diff -1.
  18.    So [0,0,0,1,2,1] and k = 2 => [0,0,0,1,3,0] and k =1
  19.    We have 3 diff of 4 and just k =1 so we can turn one 4 into a 3.
  20.    => [0,0,0,2,2,0]. Thus. the diff becomes 2 of 3 and 2 of 4.
  21.  
  22. */
  23.  
  24. class Solution {
  25. public:
  26.     long long minSumSquareDiff(vector<int>& nums1, vector<int>& nums2, int k1, int k2) {
  27.         int n = nums1.size(),M=INT_MIN;
  28.         vector<int> diff(n);
  29.         for(int i = 0; i<n; ++i) {
  30.             diff[i] = abs(nums1[i] - nums2[i]);  //This line is storing difference in normal array
  31.             M=max(diff[i],M);    //finding the maximum difference to make the actual array.
  32.         }
  33.         vector<int> bucket(M+1);
  34.         for(int i = 0 ; i<n; ++i) {
  35.             bucket[diff[i]]++;   //Here count of all difference is stored at index difference.
  36.         }
  37.         int k = k1 + k2;
  38.         for(int i = M; i > 0 && k>0; --i) {
  39.             if(bucket[i] > 0) {
  40.                 int minus = min(bucket[i], k);
  41.                 bucket[i] -= minus;
  42.                 bucket[i-1] += minus;
  43.                 k -= minus;
  44.             }
  45.         }
  46.         long long ans = 0;
  47.         for(long long i = M; i > 0; --i) {
  48.             ans += bucket[i]*i*i;
  49.         }
  50.         return ans;
  51.    
  52.     }
  53. };
  54.  
  55.  
  56.  
  57.  
  58.  
  59.  
  60.  
  61.  
  62.  
  63.  
  64.  
  65.  
  66.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement