Maximum Product Subarray

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.

 
比较费思量!
思路: 设两个辅助变量pos 和 neg,首先用0把数组分段,遇到0就把pos 和 neg 归零,然后分正负数来分别更新pos和neg。

public class Solution {
public int maxProduct(int[] A) {
if(A == null || A.length == 0) return 0;
int result = A[0];
int pos = Math.max(0, A[0]);
int neg = Math.min(0, A[0]);
for(int i = 1; i < A.length; i++) {
if(A[i] == 0) {
pos = 0;
neg = 0;
} else if(A[i] > 0) {
pos = Math.max(A[i], pos * A[i]);
neg = neg * A[i];
} else {
int old_pos = pos;
pos = neg * A[i];
neg = Math.min(A[i], old_pos * A[i]);
}
result = Math.max(result, pos);
}
return result;
}
}

posted @ 2014-12-30 11:56  江南第一少  阅读(126)  评论(0)    收藏  举报