1818. Minimum Absolute Sum Difference
Description
You are given two positive integer arrays nums1
and nums2
, both of length n
.
The absolute sum difference of arrays nums1
and nums2
is defined as the sum of |nums1[i] - nums2[i]|
for each 0 <= i < n
(0-indexed).
You can replace at most one element of nums1
with any other element in nums1
to minimize the absolute sum difference.
Return the minimum absolute sum difference after replacing at most oneelement in the array nums1
. Since the answer may be large, return it modulo 109 + 7
.
|x|
is defined as:
x
ifx >= 0
, or-x
ifx < 0
.
Example 1:
Input: nums1 = [1,7,5], nums2 = [2,3,5]
Output: 3
Explanation: There are two possible optimal solutions:
- Replace the second element with the first: [1,7,5] => [1,1,5], or
- Replace the second element with the third: [1,7,5] => [1,5,5].
Both will yield an absolute sum difference of |1-2| + (|1-3| or |5-3|) + |5-5| =
3.
Example 2:
Input: nums1 = [2,4,6,8,10], nums2 = [2,4,6,8,10] Output: 0 Explanation: nums1 is equal to nums2 so no replacement is needed. This will result in an absolute sum difference of 0.
Example 3:
Input: nums1 = [1,10,4,4,2,7], nums2 = [9,3,5,1,7,4]
Output: 20
Explanation: Replace the first element with the second: [1,10,4,4,2,7] => [10,10,4,4,2,7].
This yields an absolute sum difference of |10-9| + |10-3| + |4-5| + |4-1| + |2-7| + |7-4| = 20
Constraints:
n == nums1.length
n == nums2.length
1 <= n <= 105
1 <= nums1[i], nums2[i] <= 105
Solutions
Solution: Binary Search
- Time complexity: O(nlogn)
- Space complexity: O(n)
JavaScript
js
/**
* @param {number[]} nums1
* @param {number[]} nums2
* @return {number}
*/
const minAbsoluteSumDiff = function (nums1, nums2) {
const MODULO = 10 ** 9 + 7;
const clone = [...nums1].sort((a, b) => a - b);
const size = nums1.length;
const findNearPosition = target => {
let left = 0;
let right = size - 1;
if (clone[right] < target) return right + 1;
while (left < right) {
const mid = Math.floor((left + right) / 2);
clone[mid] < target ? (left = mid + 1) : (right = mid);
}
return left;
};
let result = (max = 0);
for (let index = 0; index < size; index++) {
const a = nums1[index];
const b = nums2[index];
const diff = Math.abs(a - b);
result = (result + diff) % MODULO;
const absolute = findNearPosition(b);
const next = clone[absolute] ? clone[absolute] - b : diff;
const previous = clone[absolute - 1] ? b - clone[absolute - 1] : diff;
max = Math.max(max, diff - next, diff - previous);
}
return (result + MODULO - max) % MODULO;
};