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
.spa
此題要求是要在一個無需的數組找出一個乘積最大的連續子數組code
例如[2,3,-2,4],由於可能有負數,能夠設置兩個臨時變量mint和maxt,mint存儲遇到負數以後相乘變小的乘積,maxt用來存儲大的乘積。blog
好比2*3=6,此時,mint = maxt = 6,當下次遇到-2時,mint = maxt = -12,此時乘積-12小於-2,則應使maxt = -2。爲避免下個數仍是負數,應使mint不變,若下次遇到負數,則乘積比maxt大,而後交換……it
具體看代碼:io
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 }