Maintained by Vikas Dulgunde, software engineer
You are given an array of integers. A subarray is a run of one or more values that sit next to each other in the original order, with nothing skipped in between. Your job is to look at every possible run and report the biggest product any of them can produce.
The numbers can be positive, negative, or zero, and that mix is what makes the problem interesting. A negative value can flip a large positive product into a large negative one, but a second negative later on can flip it right back to a large positive. A zero wipes out any running product entirely.
Because the answer can come from a run that starts anywhere, you cannot simply multiply everything together. You need to track how the product evolves as you move across the array and decide, at each step, whether extending the current run or starting fresh gives you more.
Return the single integer that is the maximum product found across all valid subarrays.
The run [2, 3] multiplies to 6. Extending into -2 would drop the product to -12, and the lone 4 only gives 4, so 6 is the best.
Taking the whole array, (-2) * 3 * (-4) = 24. The two negatives cancel their signs, so the full run beats any shorter piece.
The 0 breaks the array into [-2] and [-1], each negative. No contiguous run beats the single 0, so the answer is 0.
Visible test cases
A negative number does not just shrink a product, it swaps which extreme matters: the smallest (most negative) running product can become the largest after one more negative.
So at each index track two values together, the largest product ending here and the smallest product ending here, instead of only the maximum.
When the current number is negative, swap your running max and min before updating, since multiplying by a negative turns the smallest into the largest and vice versa. Reset by comparing against the number itself to handle zeros and fresh starts.
Try every start index, extend to every end index, multiply the run as you go, and keep the best product seen.
Carry both the maximum and minimum product ending at the current position. The minimum matters because a future negative can turn the most negative product into the largest.