|
3 | 3 | * @param {number[]} nums2
|
4 | 4 | * @return {number}
|
5 | 5 | */
|
6 |
| -const minAbsoluteSumDiff = function(nums1, nums2) { |
7 |
| - let sum = 0, lgDiff = -Infinity, idx = -1 |
| 6 | +const minAbsoluteSumDiff = function (A, B) { |
8 | 7 | const mod = 10 ** 9 + 7
|
9 |
| - const n = nums1.length, { min, max, abs } = Math |
10 |
| - for(let i = 0; i < n; i++) { |
11 |
| - let tmp = abs(nums1[i] - nums2[i]) |
12 |
| - if(tmp > lgDiff) lgDiff = tmp, idx = i |
13 |
| - sum = (sum + tmp) % mod |
| 8 | + const sA = [...A].sort((a, b) => a - b) |
| 9 | + let res = 0 |
| 10 | + let gain = 0 |
| 11 | + |
| 12 | + for (let i = 0; i < A.length; i++) { |
| 13 | + const delta = Math.abs(A[i] - B[i]) |
| 14 | + res += delta |
| 15 | + // if delta <= gain, delta - newDelta is not possbile to be better than gain |
| 16 | + if (delta <= gain) continue |
| 17 | + // Find closest to B[i] in A |
| 18 | + const idx = binaryS(sA, B[i]) |
| 19 | + // Double check l, l + 1, l - 1 |
| 20 | + const newDelta = Math.min( |
| 21 | + Math.abs(sA[idx] - B[i]), |
| 22 | + idx >= 1 ? Math.abs(sA[idx - 1] - B[i]) : Infinity, |
| 23 | + idx + 1 < A.length ? Math.abs(sA[idx + 1] - B[i]) : Infinity |
| 24 | + ) |
| 25 | + gain = Math.max(gain, delta - newDelta) |
14 | 26 | }
|
15 |
| - |
16 |
| - let res = sum, delta = lgDiff, t = Infinity |
17 |
| - for(let i = 0; i < n; i++) { |
18 |
| - if(i !== idx) { |
19 |
| - const t1 = abs(nums1[i] - nums2[idx]) |
20 |
| - // const t2 = abs(nums2[i] - nums1[idx]) |
21 |
| - const tmp = min(t1, lgDiff) |
22 |
| - if(tmp < t) t = tmp |
23 |
| - } |
| 27 | + return (res - gain) % mod |
| 28 | +} |
| 29 | +function binaryS(A, b) { |
| 30 | + let [l, r] = [0, A.length - 1] |
| 31 | + while (l < r) { |
| 32 | + const mid = l + ((r - l) >> 1) |
| 33 | + const midV = A[mid] |
| 34 | + if (midV === b) return mid |
| 35 | + if (midV < b) l = mid + 1 |
| 36 | + else r = mid - 1 |
24 | 37 | }
|
25 |
| - // console.log(sum, lgDiff, idx, t) |
26 |
| - return (sum - lgDiff + t) % mod |
27 |
| - |
28 |
| -}; |
| 38 | + return l |
| 39 | +} |
0 commit comments