您的位置:首页 > 其它

152. Maximum Product Subarray

2016-02-27 03:02 295 查看
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
.

Solution 1

public static int maxProduct(int[] nums) {
if (nums.length == 0) {
return 0;
}

int maxherepre = nums[0];
int minherepre = nums[0];
int maxsofar = nums[0];
int maxhere, minhere;

for (int i = 1; i < nums.length; i++) {
maxhere = Math.max(Math.max(maxherepre * nums[i], minherepre * nums[i]), nums[i]);
minhere = Math.min(Math.min(maxherepre * nums[i], minherepre * nums[i]), nums[i]);
maxsofar = Math.max(maxhere, maxsofar);
maxherepre = maxhere;
minherepre = minhere;
}
return maxsofar;
}

Solution 2 Same as above
public int maxProduct3(int[] nums) {
int result = nums[0];
int max = nums[0];
int min = nums[0];
for(int i = 1; i < nums.length; i++){
int temp = max;
max = Math.max(Math.max(max * nums[i], min * nums[i]), nums[i]);
min = Math.min(Math.min(temp * nums[i], min * nums[i]), nums[i]);
if(max > result){
result = max;
}
}
return result;
}
Solution 3

public static int maxProduct2(int[] nums) {
int n = nums.length;
int r = nums[0];
for (int i = 1, imax = r, imin = r; i < n; i++) {
if(nums[i] < 0){
int temp = imax;
imax = imin;
imin = temp;
}
imax = Math.max(nums[i], imax * nums[i]);
imin = Math.min(nums[i], imin * nums[i]);
r = Math.max(r, imax);
}
return r;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: