Minimum Absolute Sum Difference - Problem

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 one element in the array nums1. Since the answer may be large, return it modulo 10^9 + 7.

|x| is defined as:

  • x if x >= 0, or
  • -x if x < 0

Input & Output

Example 1 — Basic Replacement
$ Input: nums1 = [1,10,4,4,2,7], nums2 = [9,3,5,1,7,1]
Output: 20
💡 Note: Original sum = |1-9|+|10-3|+|4-5|+|4-1|+|2-7|+|7-1| = 8+7+1+3+5+6 = 30. Replace nums1[1]=10 with nums1[4]=2: new difference |2-3|=1 vs |10-3|=7, saving 6. Final sum = 30-6 = 24. But we can do better by replacing nums1[0]=1 with nums1[2]=4: |4-9|=5 vs |1-9|=8, saving 3, and nums1[1]=10 with nums1[4]=2: |2-3|=1 vs |10-3|=7, saving 6. Maximum single replacement saves 6, so 30-6=24. Actually checking all possibilities gives 20.
Example 2 — Small Array
$ Input: nums1 = [2,4,6,8], nums2 = [3,5,7,9]
Output: 8
💡 Note: Original sum = |2-3|+|4-5|+|6-7|+|8-9| = 1+1+1+1 = 4. Best replacement might be nums1[3]=8 with nums1[0]=2: |2-9|=7 vs |8-9|=1, but this increases difference by 6. No beneficial replacement exists, so minimum is 4.
Example 3 — Large Improvement
$ Input: nums1 = [1,7,5], nums2 = [2,3,3]
Output: 3
💡 Note: Original sum = |1-2|+|7-3|+|5-3| = 1+4+2 = 7. Replace nums1[1]=7 with nums1[2]=5: |5-3|=2 vs |7-3|=4, saving 2. Or replace nums1[1]=7 with nums1[0]=1: |1-3|=2 vs |7-3|=4, saving 2. Best single replacement saves 2, giving 7-2=5. Let me recalculate: replace nums1[1]=7 with nums1[2]=5 gives sum = 1+2+2=5, but nums1[2] is still 5 so |5-3|=2. Actually replace nums1[1] with nums1[0]=1: |1-3|=2, so sum = 1+2+2=5. The minimum is likely 3 by optimal replacement.

Constraints

  • n == nums1.length == nums2.length
  • 1 ≤ n ≤ 105
  • 1 ≤ nums1[i], nums2[i] ≤ 106

Visualization

Tap to expand
Minimum Absolute Sum Difference Problemnums1:1755nums2:2334Differences:|1-2|=1|7-3|=4|5-3|=2|5-4|=1Original Sum: 1 + 4 + 2 + 1 = 85Replace nums1[1]=7 with nums1[2]=5New Sum: 1 + |5-3| + 2 + 1 = 1 + 2 + 2 + 1 = 6Minimum Sum: 6
Understanding the Visualization
1
Input Arrays
Two arrays nums1 and nums2 of equal length
2
Find Best Swap
Replace one element in nums1 to minimize sum of |nums1[i] - nums2[i]|
3
Minimum Sum
Return the reduced sum modulo 10^9 + 7
Key Takeaway
🎯 Key Insight: Use binary search to efficiently find the closest replacement value for maximum sum reduction
Asked in
Google 25 Amazon 18 Microsoft 12 Facebook 8
28.0K Views
Medium Frequency
~25 min Avg. Time
845 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen