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
.
这也是一个DP问题。max记录到前继节点的最大乘积,min记录到前继节点的最小乘积,mps记录全局的最大乘积。
max = Max(A[i], A[i]*max, A[i]*min), min = Min(A[i], A[i]*max, A[i]*min)。注意在更新max之前用一个临时变量保存max原来的值。
Solution:
public class Solution {
public int maxProduct(int[] A) {
if(A==null||A.length==0)
return 0;
int max = A[0],min = A[0],mps = A[0];
for(int i=1;i<A.length;i++)
{
int tmp = max;
max = Math.max(Math.max(A[i], A[i]*max),A[i]*min);
min = Math.min(Math.min(A[i], A[i]*tmp),A[i]*min);
if(max>mps)
mps = max;
}
return mps;
}
}