Equal Sum Arrays With Minimum Number of Operations LeetCode solution in JavaScript

1
var minOperations = function (nums1, nums2) {
2
/*
3
Two impossible cases:
4
min1...max1 ... min2...max2 -> we can't make them equal
5
min2...max2 ... min1...max1 -> we can't make them equal
6
*/
7
let min1 = nums1.length * 1;
8
let max1 = nums1.length * 6;
9
let min2 = nums2.length * 1;
10
let max2 = nums2.length * 6;
11
if (min2 > max1 || min1 > max2) {
12
return -1;
13
}
14
let sum1 = nums1.reduce((acc, cur) => acc + cur);
15
let sum2 = nums2.reduce((acc, cur) => acc + cur);
16
if (sum1 === sum2) return 0;
17
if (sum1 < sum2) {
18
return helper(nums1, nums2, sum1, sum2);
19
} else {
20
return helper(nums2, nums1, sum2, sum1);
21
}
22
// T.C: O(M + N), M = # of nums1, N = # of nums2
23
// S.C: O(1)
24
};
25

26
// Condition: sum of A < sum of B
27
// the idea is to add the maximum possible value to sumA and
28
// subtract the maximum possible value from sumB so that
29
// we make sumA >= sumB as soon as possible
30
function helper(A, B, sumA, sumB) {
31
let freqA = new Array(7).fill(0);
32
let freqB = new Array(7).fill(0);
33
for (let i = 0; i < A.length; i++) {
34
freqA[A[i]]++;
35
}
36
for (let i = 0; i < B.length; i++) {
37
freqB[B[i]]++;
38
}
39
let count = 0;
40
for (let i = 1; i <= 6; i++) {
41
// increase sumA
42
while (freqA[i] > 0 && sumA < sumB) {
43
sumA += 6 - i;
44
freqA[i]--;
45
count++;
46
}
47
let j = 7 - i;
48
// decrease sumB
49
while (freqB[j] > 0 && sumA < sumB) {
50
sumB -= j - 1;
51
freqB[j]--;
52
count++;
53
}
54
if (sumA >= sumB) break;
55
}
56
return count;
57
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0