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
.
This requirement is to find a continuous sub-array with the maximum product in an unnecessary array.
For example, [2, 3,-2, 4], because there may be negative numbers, you can set two temporary variables mint and maxt. Mint stores the product that is multiplied by a negative number, and maxt stores the large product.
For example, 2*3 = 6. At this time, mint = maxt = 6. When-2 is encountered next time, mint = maxt =-12. At this time, the product-12 is less than-2, make maxt =-2. To avoid the number or negative number, mint should be kept unchanged. If a negative number is encountered next time, the product is larger than maxt, and then exchanges ......
Specific Code:
1 public class Solution { 2 public int maxProduct(int[] A) { 3 int n = A.length; 4 int mint = 1; 5 int maxt = 1; 6 7 int maxvalue = A[0]; 8 for(int i = 0 ; i < n ; i++){ 9 if(A[i] == 0){10 mint = 1;11 maxt = 1;12 if(maxvalue < 0)13 maxvalue = 0;14 }else{15 int curmax = maxt * A[i];16 int curmin = mint * A[i];17 18 maxt = curmax > curmin ? curmax : curmin;19 mint = curmax > curmin ? curmin : curmax;20 21 if(maxt < A[i])22 maxt = A[i];23 24 if(mint > A[i])25 mint = A[i];26 27 if(maxt > maxvalue)28 maxvalue = maxt;29 }30 }31 32 return maxvalue;33 34 }35 }
Maximum Product subarray maximum continuous product subset