您的位置:首页 > 其它

Maximum Product subarray | LeetCode

2015-11-22 19:40 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
.

solution implement by java:

解答思路:每次选择一个元素都是如果该元素使得乘积变大则加入,否则不乘,所以我们需要两个变量分别用来记录在决定当前元素是否需要乘的时候,前面子串所得到的最小值和最大值,每次乘积结果都再用一个变量来存取记录,最后走完整个过程,记录下来的最大值就是结果。

public int maxProduct(int[] nums) {

if(nums.length==1)

return nums[0];

int left=nums[0];

int right=nums[0];

int maxpro=nums[0];

int max,min;

for(int i=1;i<nums.length;++i){

max=Math.max(Math.max(left*nums[i],right*nums[i]),nums[i]);

min=Math.min(Math.min(left*nums[i],right*nums[i]),nums[i]);

maxpro=Math.max(max,maxpro);

left=max;

right=min;

}

return maxpro;

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