Python 基礎知識簡單

最小絕對差之和

“最小總和絕對差”問題的詳細指南和 Python 實作。

問題陳述

簡單

寫一個函數 min_sum_abs_diff(arr1, arr2) ,它接受兩個長度相等的數組,並在以任意順序重新排列兩個數組的元素後返回 sum(|arr1[i] - arr2[i]|) 的最小可能值。若要最小化此總和,請將同一索引處的陣列和對元素進行排序。

約束條件
  • 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?
考慮使用特定於數組的資料結構,例如集合或堆。
Edge Cases to Watch
  • 空輸入結構
  • 單元素輸入
  • 大數值範圍

準備好解決了嗎?

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 資源

透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。