本文完整拆解 LeetCode 152 Maximum Product Subarray 的解法:從解題思路、演算法步驟到時間與空間複雜度,並整理邊界情況與 3 種解法比較,幫你把 Maximum Product Subarray 一次弄懂。
Explore diverse LeetCode solutions in Python, C++, JavaScript, SQL, and TypeScript. Ideal for interview prep, learning, and code practice in multiple programming languages. Github Repo Link
Given an integer array nums, find a subarray that has the largest product, and return the product.
The test cases are generated so that the answer will fit in a 32-bitinteger.
Example 1:
Input: nums = [2,3,-2,4] Output: 6 Explanation: [2,3] has the largest product 6.
Example 2:
Input: nums = [-2,0,-1] Output: 0 Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
Constraints:
1 <= nums.length <= 2*104-10 <= nums[i] <= 10- The product of any subarray of
numsis guaranteed to fit in a 32-bit integer.
Python
# time complexity: O(n)
# space complexity: O(1)
from typing import List
class Solution:
def maxProduct(self, nums: List[int]) -> int:
if len(nums) == 0:
return 0
maxSoFar, minSoFar, result = nums[0], nums[0], nums[0]
for i in range(1, len(nums)):
curr = nums[i]
tempMax = max(curr, max(maxSoFar * curr, minSoFar * curr))
minSoFar = min(curr, min(maxSoFar * curr, minSoFar * curr))
maxSoFar = tempMax
result = max(result, maxSoFar)
return result
nums = [-2, 0, -1]
print(Solution().maxProduct(nums))
Maximum Product Subarray 解題思路
和最大子陣列和不同,乘積會被負號翻轉:一個很小的負數乘上另一個負數會變成很大的正數。所以必須同時追蹤「到目前為止的最大乘積」與「最小乘積」,遇到負數時把兩者交換,這樣最小值才有機會翻身成為最大值。
Maximum Product Subarray 演算法步驟
- 初始化 maxProd、minProd、answer 都等於 nums[0]。
- 從索引 1 開始走訪,若 nums[i] 為負數就交換 maxProd 與 minProd。
- 令 maxProd = max(nums[i], maxProd * nums[i]),minProd = min(nums[i], minProd * nums[i])。
- 用 maxProd 更新 answer,走完後回傳 answer。
Maximum Product Subarray 複雜度分析
| 項目 | 複雜度 |
|---|---|
| 時間複雜度 | O(n) |
| 空間複雜度 | O(1) |
單次線性掃描,每步做常數次比較與乘法,時間 O(n)、空間 O(1)。關鍵不在複雜度而在「同時維護最大與最小」這個狀態設計。
Maximum Product Subarray 的邊界情況與常見錯誤
- 遇到 0 時 maxProd 與 minProd 都會被重設為 0,下一個元素會自然重新開始。
- 全部為負數時答案可能是單一元素,所以 answer 要用 nums[0] 初始化而非 0。
- 交換一定要在更新之前,順序顛倒會算錯。
- 乘積可能溢位,注意數值型別。
Maximum Product Subarray 其他解法比較
| 解法 | 時間 | 空間 | 說明 |
|---|---|---|---|
| 雙層迴圈列舉所有子陣列 | O(n²) | O(1) | 最直覺但會超時 |
| 前綴積 + 從左右各掃一次 | O(n) | O(1) | 處理 0 的切分較繁瑣 |
| 同時追蹤最大與最小 | O(n) | O(1) | 本文採用 |
