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 .
MLGB, today encountered this problem to engage in a long day. Recorded.
First liberation can use the poor lift. A two-dimensional array product[i][j] records the product from I to J, and then iterates over the largest element in the array, which is the answer.
Public intMaxproduct (int[] A) {int[] Product =New int[A.length][a.length]; intmax = A[0]; for(inti = 0; i < a.length; i++) {Product[i][i]=A[i]; for(intj = i + 1; J < A.length; J + +) {Product[i][j]= product[i][j-1] *A[j]; Max=Math.max (Max, product[i][j]); } Max=Math.max (Max, a[i]); } returnMax; }
Simple and clear. But of course it's time out.
Then the master thought for a long time, during the period also saw the film.
Assuming that the element i is a positive number, then we want to calculate the maximum product of the current I element p[i], we need to know the maximum product of the preceding i-1 p[i-1],p[i] = p[i-1] * A[i];
Assuming that the element i is a negative number, then we want to calculate the maximum product of the current I element p[i], it is necessary to know the minimum product (negative) of the preceding i-1 n[i-1], p[i] = n[i-1] * A[i];
P[i] denotes the maximum product that can be taken at the end of the element I, and n[i] represents the negative product that can be taken at the end of the element I. If the I element is a flower of 0, everything belongs to 0,p[i] = N[i] = 0.
Public intMaxProduct2 (int[] A) {if(A.length = = 1) { returnA[0]; } int[] p =New int[A.length]; int[] n =New int[A.length]; intMax =Integer.min_value; for(inti = 0; i < a.length; i++) { if(A[i] > 0) {P[i]= (i > 0 && p[i-1] > 0)? P[I-1] *A[i]: a[i]; N[i]= (i > 0 && n[i-1] < 0)? N[I-1] * A[i]: 0; } Else if(A[i] < 0) {P[i]= (i > 0 && n[i-1] < 0)? N[I-1] * A[i]: 0; N[i]= (i > 0 && p[i-1] > 0)? P[I-1] *A[i]: a[i]; } Else{Max= Math.max (max, 0); } if(P[i] > 0) {Max=Math.max (Max, p[i]); } Else if(N[i] < 0) {Max=Math.max (Max, n[i]); } } returnMax; }
Because when I met 0, it was a new starting point.
The code above can be simplified to use a constant space below the less readable code.
Public intMaxproduct (int[] A) {if(A.length = = 1) { returnA[0]; } intp = 0; intn = 0; intMax =Integer.min_value; for(inti = 0; i < a.length; i++) { intNP = p > 0? P *A[i]: a[i]; intnn = n < 0? n * A[i]: 0; if(A[i] > 0) {p=NP; N=nn; } Else if(A[i] < 0) {p=nn; N=NP; } Else{p= 0; N= 0; Max= Math.max (max, 0); Continue; } if(P > 0) {Max=Math.max (P, max); } Else if(N < 0) {Max=Math.max (n, max); } } returnMax; }
Leetcode Note Maximum Product subarray