Maximum Product Subarray

来源:互联网 发布:thinking in java 4th 编辑:程序博客网 时间:2024/06/10 16:33

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 int maxProduct(int[] nums) {if(nums==null||nums.length<=0)return 0;int max=nums[0],posMax=nums[0],negMax=nums[0];for(int i=1;i<nums.length;i++){int tmp=posMax;posMax=Math.max(Math.max(posMax*nums[i], nums[i]),negMax*nums[i]);negMax=Math.min(Math.min(tmp*nums[i], nums[i]), negMax*nums[i]);max=Math.max(posMax, max);}return max;}


0 0