Ctrl K

One Edit to the Closest Match

Medium
A weather station produced a forecast guess, and the real readings are stored in truth. Both arrays have the same length n and hold positive integers. The **gap** of the forecast is the sum of |guess[i] − truth[i]| over all positions i. You may make at most one edit: pick a position in guess and overwrite it with a value that already appears somewhere in guess. Making no edit is also allowed. Return the smallest gap you can achieve. The answer can be large, so return it modulo 10⁹ + 7.
Example 1
guess=[4, 9, 2], truth=[3, 3, 2] → 2

The current gap is |4−3| + |9−3| + |2−2| = 7. Replace 9 with 4, which is already in guess: |4−3| + |4−3| + 0 = 2.

Example 2
guess=[6, 6, 6], truth=[6, 6, 6] → 0

The arrays already match, so the gap is 0 and nothing needs to change.

Example 3
guess=[1, 10], truth=[10, 1] → 9

The gap is 18. Overwriting either element with the other, e.g. [10, 10], gives |10−10| + |10−1| = 9.

Constraints
  • 1 ≤ n ≤ 10⁵
  • guess.length = truth.length = n
  • 1 ≤ guess[i], truth[i] ≤ 10⁵
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsNearest Roomy Enough Room HardFlowers in Bloom on Visit Day HardDeal Out From the Lowest Card HardClimbing Along Rows and Columns HardTriples Under a Limit Medium
loading Python…
Input
guess=[4, 9, 2], truth=[3, 3, 2]
Expected
2

Run checks the first 3 tests in your browser. Submit checks all 87 tests on the server, hidden ones included.