SDE & MLE Prep

152. Maximum Product Subarray

Problem

Return the largest product of any non-empty contiguous subarray of nums. Values can be negative or zero.

Example: [2,3,-2,4] → 6; [-2,0,-1] → 0

Constraints: n ≤ 2·10⁴.

Track both the max and min product ending here — a negative number swaps them.

nums   2   3  -2   4
max    2   6  -2   4
min    2   3 -12 -48      best = 6

Complexity: O(n) time, O(1) space.

class Solution:
    def maxProduct(self, nums: List[int]) -> int:
        best = hi = lo = nums[0]
        for x in nums[1:]:
            cands = (x, hi * x, lo * x)
            hi, lo = max(cands), min(cands)
            best = max(best, hi)
        return best