Dynamic Programming21 sections · 916 units
Open in Course

LeetCode 152 Maximum Product Subarray - Implementation

Full solution

function maxProduct(nums)
    n := length of nums
    maxProd := nums[0]
    minProd := nums[0]
    result := nums[0]
    for i from 1 to n - 1
        if nums[i] < 0
            swap(maxProd, minProd)
        maxProd := max(nums[i], maxProd * nums[i])
        minProd := min(nums[i], minProd * nums[i])
        result := max(result, maxProd)
    return result

The swap handles the sign flip elegantly. When nums[i]nums[i] is negative, what was maximum becomes minimum and vice versa. Then you apply the standard recurrence.

we only need two variables, not arrays. Each position only depends on the previous one. This is the same space reduction pattern you saw in Fibonacci and Climbing Stairs.

Time: O(n)O(n). Space: O(1)O(1).