Given an integer array nums, find a subarray with the largest product and return the product. Negative × negative = positive, so track both max and min.
[2,3,-2,4]6[-2,3,-4]24Unlike sum, a negative product can flip to max when multiplied by another negative. Track both max and min product ending here. At each step, new max = n, old max×n, or old min×n.
Multiplying every subarray is O(n²). Kadane style tracking of only the maximum fails, because a negative number turns the smallest product into the largest.
Track two values for subarrays ending at the current index: the largest product and the smallest product. The smallest one matters because it may be a big negative number. When the current number is negative, swap the two before updating. Then the new maximum is the larger of the number itself and the maximum times the number, and the minimum likewise. Keep the best maximum seen anywhere.
With products, keep both the maximum and the minimum. A negative number swaps their roles.
Run the animation above on your own input, or watch the 1:54 video explanation of Maximum Product Subarray with a dry run and Java code.