Python Basics簡単

Minimum sum absolute difference

Detailed guide and Python implementation for the 'Minimum sum absolute difference' problem.

問題提起

簡単

Write a function min_sum_abs_diff(arr1, arr2) that takes two arrays of equal length and returns the minimum possible value of sum(|arr1[i] - arr2[i]|) after rearranging elements of both arrays in any order. To minimize this sum, sort both arrays and pair elements at the same index.

制約
  • 1 <= len(arr1) == len(arr2) <= 10^5
  • -10^9 <= arr1[i], arr2[i] <= 10^9

Example 1
Input
arr1 = [4, 1, 8, 7], arr2 = [2, 3, 6, 5]
Output
6
Explanation

Sort arr1: [1,4,7,8]. Sort arr2: [2,3,5,6]. Sum: |1-2|+|4-3|+|7-5|+|8-6| = 1+1+2+2 = 6.

Example 2
Input
arr1 = [1, 2, 3], arr2 = [1, 2, 3]
Output
0
Explanation

Same arrays, so differences are all zero.

Example 3
Input
arr1 = [5, 5], arr2 = [5, 5]
Output
0
Explanation

All pairs match perfectly.

Need a Hint?
Consider using Arrays-specific data structures like sets or heaps.
Edge Cases to Watch
  • Empty input structures
  • Single element inputs
  • Large numerical bounds

解決する準備はできましたか?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

エディタで開く
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推奨される Python リソース

関連するインタラクティブなチュートリアル、チートシート、コード比較で知識を深めてください。