Blind 75 · #56 · 1-D Dynamic Programming

Maximum Product Subarray

MediumTrack max and minTime O(n)Space O(1)

Maximum Product Subarray is a medium 1-D Dynamic Programming problem from the Blind 75. The key pattern is track max and min, and a good solution runs in O(n) time.

Problem

Return the largest product of a non-empty contiguous subarray.

Examples

Example 1

Input

[-2,3,-4]

Output

24

Example 2

Input

[3,5,-1,2]

Output

15

Example 3

Input

[-2]

Output

-2

Approach

Keep both the largest and smallest product ending at each position, because a negative number swaps them.

PatternTrack max and min
TimeO(n)
SpaceO(1)

Watch out for

Zeros reset both running products.

More 1-D Dynamic Programming problems