Maximum Product Subarray
This problem asks for the biggest product you can make from one continuous part of the list. A product means you multiply the numbers together, not add them. The chosen numbers must stay next to each other, because you are looking for a subarray.
This puzzle gets interesting because negative numbers can completely change the result. A negative number can make the product smaller, but two negatives together can suddenly turn the product positive again. Zero can also break a streak, because multiplying by zero resets everything to zero.
For example, in [2,3,-2,4], the best answer is 6 from the subarray [2,3]. If you keep going and include -2, the product changes in a bad way. But in [-2,3,-4], the full subarray gives 24, because -2 × 3 × -4 = 24. In [-2,0,-1], the best answer is 0, since the zero beats the other possible products.
The answer is only the largest product value. You do not need to return the subarray itself, just the best number you can get.
Example Input & Output
Example with input: nums = [2,3,-2,4]
Example with input: nums = [-2,3,-4]
Example with input: nums = [-2,0,-1]
Algorithm Flow

Best Answers
class Solution {
public int max_product(int[] nums) {
if (nums.length == 0) return 0;
int res = nums[0], maxP = nums[0], minP = nums[0];
for (int i = 1; i < nums.length; i++) {
int x = nums[i];
if (x < 0) {
int tmp = maxP; maxP = minP; minP = tmp;
}
maxP = Math.max(x, maxP * x);
minP = Math.min(x, minP * x);
res = Math.max(res, maxP);
}
return res;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
