public class Solution {
public int maxProduct(int[] nums) {
int maxValue = nums[0];
int minValue = nums[0];
int max = nums[0];
for(int i = 1; i < nums.length; i++){
int maxValueProduct = maxValue * nums[i];
int minValueProduct = minValue * nums[i];
maxValue = Math.max(maxValueProduct,Math.max(minValueProduct, nums[i]));
minValue = Math.min(maxValueProduct,Math.min(minValueProduct, nums[i]));
if(maxValue > max)
max = maxValue;
}
return max;
}
}
Find the contiguous subarray within an array (containing at least one number) which has the largest product.
For example, given the array [2,3,-2,4]
,
the contiguous subarray [2,3]
has the largest product = 6
.