競賽程式設計

最大絕對差之和

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

問題陳述

寫一個函數 max_sum_abs_diff(arr),傳回數組 arr 的任何循環排列中連續元素的絕對差的最大和。

約束條件
  • 2 <= len(arr) <= 1000
  • -10^4 <= arr[i] <= 10^4

範例

Example 1
Input
max_sum_abs_diff([1, 2, 4, 8])
Output
18
Explanation

The circular permutation [1, 8, 2, 4] yields |1-8| + |8-2| + |2-4| + |4-1| = 7 + 6 + 2 + 3 = 18.

Example 2
Input
max_sum_abs_diff([10, 12])
Output
4
Explanation

The only circular permutation is [10, 12] yielding |10-12| + |12-10| = 2 + 2 = 4.

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

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