1486. One Swap Closer
Two equally long arrays of sensor readings, a and b, should match as closely as possible. Their mismatch is the sum of |a[i] - b[i]| over all positions. Before comparing, you may pick at most one position i and overwrite a[i] with a copy of any value that originally appears somewhere in a (choosing a[i] itself changes nothing).
Return the smallest mismatch you can reach, as a 64-bit integer with no modulo. Sort a copy of a and, for every b[i], binary search the closest available value to find how much that single position could save; then apply the best saving. Expected time is O(n log n) with O(n) extra space.
Example 1
- Input:
- a = [1,10,4], b = [1,2,4]
- Output:
- 1
- Explanation:
Overwriting the 10 with a copy of 1 makes its gap to 2 equal to 1, so the total drops from 8 to 1.
Example 2
- Input:
- a = [3], b = [8]
- Output:
- 5
- Explanation:
The only element can only be replaced by itself, so the total stays 5.
Example 3
- Input:
- a = [5,5], b = [5,5]
- Output:
- 0
- Explanation:
Everything already matches, so the total is 0.
Constraints
1 ≤ n ≤ 105
a.length == b.length
0 ≤ a[i], b[i] ≤ 109
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms
Expected complexity
- Time
- O(n log n)
- Space
- O(n)