[leedcode 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) {
        //因为本题求的是乘积最大,所以需要维护当前最大值和当前最小值,而且是在nums[i]**,curMax*nums[i],curMin*nums[i]中取即可
        //需要变量res,保存中间最大的结果。
       
        if(nums.length<1) return 0;
        int curMax=nums[0];
        int curMin=nums[0];
        int max=nums[0];
         int res=nums[0];
        for(int i=1;i<nums.length;i++){
            int temp=curMax*nums[i];
            int ttemp=curMin*nums[i];
            curMax=Math.max(nums[i],Math.max(temp,ttemp));
            curMin=Math.min(nums[i],Math.min(ttemp,temp));
            res=Math.max(res,curMax);
        }
        return res;
    }
}

 

posted @ 2015-07-21 18:34  ~每天进步一点点~  阅读(76)  评论(0编辑  收藏  举报