您的位置:首页 > 其它

Leetcode no. 152

2016-05-29 19:09 260 查看
152. 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
.

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