码迷,mamicode.com
首页 > 编程语言 > 详细

Java for LeetCode 152 Maximum Product Subarray

时间:2015-06-05 13:35:21      阅读:133      评论:0      收藏:0      [点我收藏+]

标签:

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.

解题思路:

计算连续的积最大,由于会有负数出现,因此需要用两个int表示包含nums[i]的最大值和最小值,然后res=Math.max(res, max)即可,JAVA实现如下:

    public int maxProduct(int[] nums) {
    	if(nums.length==1)
    		return nums[0];
    	int max=nums[0],min=nums[0],res=nums[0],maxTemp=0,mintemp=0;
        for(int i=1;i<nums.length;i++){
        	maxTemp=max*nums[i];
        	mintemp=min*nums[i];
        	max=Math.max(nums[i],Math.max(maxTemp, mintemp));
        	min=Math.min(nums[i],Math.min(maxTemp, mintemp));
        	res=Math.max(res, max);
        }
        return res;
    }

 

Java for LeetCode 152 Maximum Product Subarray

标签:

原文地址:http://www.cnblogs.com/tonyluis/p/4554262.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!