Python 基礎知識

求最大乘積子數組

「尋找最大乘積子數組」問題的詳細指南和 Python 實作。

問題陳述

寫一個函數 max_product_subarray(arr) ,它接受整數列表 arr 並傳回任何連續子數組的最大乘積。子數組必須至少包含一個元素。

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

範例

Example 1
Input
arr = [2, 3, -2, 4]
Output
6
Explanation

The subarray [2, 3] has the maximum product: 2 * 3 = 6.

Example 2
Input
arr = [-2, 0, -1]
Output
0
Explanation

The subarray [0] gives the maximum product of 0, since all other products are negative or zero.

Example 3
Input
arr = [-2, -3, 4]
Output
24
Explanation

The entire array: (-2) * (-3) * 4 = 24? Wait, that's the subarray [-2,-3,4] = 24. Yes, two negatives multiply to positive.

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

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