codejump
MediumPro challengePythonJavaScriptTypeScript

DP — Maximum Product Subarray

AlgorithmsDynamic ProgrammingArrays

solve(nums) — return the largest product of a contiguous non-empty subarray.
The array can contain negatives and zeros.

A negative number can flip the smallest product into the largest, so track both
the maximum and the minimum product of a subarray ending at the current index.

Examples

solve([2,3,-2,4])       → 6
solve([-2,0,-1])        → 0
solve([-2])             → -2
solve([-2,3,-4])        → 24
solve([2,-5,-2,-4,3])   → 24

Sample tests

Test #1Classic example
Input: [[2,3,-2,4]]
Output: 6
Test #2A zero splits the array
Input: [[-2,0,-1]]
Output: 0
Test #3Single negative
Input: [[-2]]
Output: -2