Find the contiguous subarray within an array (containing at least one number) which have the largest product.
For example, given the array [2,3,-2,4] ,
The contiguous Subarray has the [2,3] largest product = 6 .
Problem Solving Ideas:
Calculate the maximum number of consecutive product, because there will be negative occurrences, so you need two int to represent the maximum and minimum value containing nums[i], then Res=math.max (res, max), Java implementation is as follows:
public int maxproduct (int[] nums) { if (nums.length==1) return nums[0]; int max=nums[0],min=nums[0],res=nums[0],maxtemp=0,mintemp=0; for (int i=1;i<nums.length;i++) { maxtemp=max*nums[i]; Mintemp=min*nums[i]; Max=math.max (Nums[i],math.max (maxtemp, mintemp)); Min=math.min (Nums[i],math.min (maxtemp, mintemp)); Res=math.max (res, max); } return res; }
Java for Leetcode Maximum Product Subarray