Minimum Sum of Squared Difference LeetCode solution in Java

1
class Solution {
2
/**
3
* Algorithm 1. Count the differences between each nums1[i] and nums2[i] and store them into an
4
* int[100_001], as nums is between 0 and 100_000. 2. Let's look at the example of [1,4,10,12],
5
* [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
6
* points with k = 2. As we observe, if we use the k operations on the first pair, we can decrease
7
* 3 to 1. but this would only help with 3^2 (9) -> 1. So we decrease the totam sum diff by 8.
8
* However, if we operate on the diff of 5, this would have much more impact. 5 - 1 => (4^2)25 -
9
* 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
10
* see, we need to operate on the highest diff, lowering them. 4. As we have counted them on step
11
* #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
12
* is > 0 (k1 + k2), start from the back (highest) and decrease it one group at a time. So make
13
* all 5 diffs into 4 diff, only if their cardinal is <= k. If it's greater than k, we can only
14
* 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
15
* 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
16
* and 2 of 4.
17
*/
18
public long minSumSquareDiff(int[] nums1, int[] nums2, int k1, int k2) {
19
long minSumSquare = 0;
20
int[] diffs = new int[100_001];
21
long totalDiff = 0;
22
long kSum = k1 + k2;
23
int currentDiff;
24
int maxDiff = 0;
25
for (int i = 0; i < nums1.length; i++) {
26
// get current diff.
27
currentDiff = Math.abs(nums1[i] - nums2[i]);
28
// if current diff > 0, count/store it. If not,then ignore it.
29
if (currentDiff > 0) {
30
totalDiff += currentDiff;
31
diffs[currentDiff]++;
32
maxDiff = Math.max(maxDiff, currentDiff);
33
}
34
}
35
// if kSum (k1 + k2) < totalDifferences, it means we can make all numbers/differences 0s
36
if (totalDiff <= kSum) {
37
return 0;
38
}
39
// starting from the back, from the highest difference, lower that group one by one to the
40
// previous group.
41
// we need to make all n diffs to n-1, then n-2, as long as kSum allows it.
42
for (int i = maxDiff; i > 0 && kSum > 0; i--) {
43
if (diffs[i] > 0) {
44
// if current group has more differences than the totalK, we can only move k of them to the
45
// lower level.
46
if (diffs[i] >= kSum) {
47
diffs[i] -= kSum;
48
diffs[i - 1] += kSum;
49
kSum = 0;
50
} else {
51
// else, we can make this whole group one level lower.
52
diffs[i - 1] += diffs[i];
53
kSum -= diffs[i];
54
diffs[i] = 0;
55
}
56
}
57
}
58

59
for (int i = 0; i <= maxDiff; i++) {
60
if (diffs[i] > 0) {
61
minSumSquare += (long) (Math.pow((long) i, 2)) * diffs[i];
62
}
63
}
64
return minSumSquare;
65
}
66
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0