競賽程式設計簡單

最大化數組的總和

“最大化數組總和”問題的詳細指南和 Python 實作。

問題陳述

簡單

寫一個函數 maximize_sum(arr, k),在精確執行 k 求反後傳回陣列的最大可能總和。在每次否定中,您必須選擇一個元素並將其替換為其負值。您可以多次否定同一元素。

約束條件
  • 1 <= len(arr) <= 10^5
  • 1 <= k <= 10^5
  • -10^4 <= arr[i] <= 10^4

範例

Example 1
Input
maximize_sum([-2, 0, 5, -1, 2], 4)
Output
10
Explanation

Negate -2 to 2, -1 to 1. The remaining 2 negations can be performed on 0. The array becomes [2, 0, 5, 1, 2], summing to 10.

Example 2
Input
maximize_sum([3, -1, 0, 2], 3)
Output
6
Explanation

Negate -1 to 1. The remaining 2 negations are performed on 0. Sum is 3 + 1 + 0 + 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 資源

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