競賽程式設計簡單

最小和絕對差對

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

問題陳述

簡單

寫一個函數 min_sum_abs_diff_pairs(arr1, arr2) ,它接受兩個長度相同的數組,對它們進行排序,並將相應的元素配對以最小化它們的絕對差之和。傳回這個最小總和。

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

範例

Example 1
Input
min_sum_abs_diff_pairs([3, 2, 1], [2, 1, 3])
Output
0
Explanation

Sort both arrays: [1, 2, 3] and [1, 2, 3]. Diffs: |1-1| + |2-2| + |3-3| = 0.

Example 2
Input
min_sum_abs_diff_pairs([4, 1, 8, 7], [2, 3, 6, 5])
Output
6
Explanation

Sorted arrays: [1, 4, 7, 8] and [2, 3, 5, 6]. Diffs: |1-2| + |4-3| + |7-5| + |8-6| = 1 + 1 + 2 + 2 = 6.

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

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