您的位置:首页 > 其它

Leetcode 152 Maximum Product Subarray

2017-06-09 18:07 381 查看
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的问题,但是值得注意的是,负数和负数相乘有可能是是个大的结果

于是min和max都要存下来

public class Solution {
public int maxProduct(int[] nums) {
if(nums == null){
return 0;
}
int result = nums[0];
int min = nums[0];
int max = nums[0];
for(int i = 1; i < nums.length; i++){
int temp = min;
min = Math.min(nums[i], Math.min(nums[i] * min, nums[i]*max));
max = Math.max(nums[i], Math.max(nums[i] * temp, nums[i]*max));
result = result > max ? result : max;
}

return result;

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: