The fix is to track two values at each position:
: the maximum product of any subarray ending at index
: the minimum product (most negative) of any subarray ending at index
Why track the minimum? Because When hit a negative number, the minimum becomes the maximum and vice versa. The most negative product, multiplied by a negative, becomes the most positive.
the recurrence Each position :
Each position has three choices: start fresh with , extend the previous maximum, or extend the previous minimum. You take the best for max and the worst for min.