DevPath

← All problems

Maximum Product Subarray

Medium dynamic-programming · arrays

Description

Return the largest product of any contiguous subarray.

Constraints

1 <= n <= 20000

Examples

Input: nums = [2,3,-2,4]

Output: 6

Hints (1)
  • Track both the maximum and minimum product ending here, because a negative can flip.

Solutions

Track max and min products. · Time O(n) · Space O(1)

func maxProduct(nums []int) int {
    best, mx, mn := nums[0], nums[0], nums[0]
    for i := 1; i < len(nums); i++ {
        n := nums[i]
        a, b := mx*n, mn*n
        hi, lo := n, n
        if a > hi {
            hi = a
        }
        if b > hi {
            hi = b
        }
        if a < lo {
            lo = a
        }
        if b < lo {
            lo = b
        }
        mx, mn = hi, lo
        if mx > best {
            best = mx
        }
    }
    return best
}

Create a free account to submit solutions, track progress and save problems.

Create account