码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode Maximum Product Subarray

时间:2014-11-29 07:08:33      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   ar   color   os   sp   java   

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.

思路分析:这题与LeetCode Maximum Subarray类似,只是要注意两个负数的乘积可能变成一个很大的正数,因此要同时维护maxLocal和minLocal以及maxGlobal,初值为A[0],之后从A[1]开始遍历,maxLocal取A[i],A[i]*maxLocal.A[i]*minLocal中的最大,minLocal取A[i],A[i]*maxLocal.A[i]*minLocal中的最小,maxGlobal则是始终保存maxLocal中的最大值。要注意,更新minLocal时要用到原始的maxLocal的拷贝,而不是更新之后的值。

AC Code:

public class Solution {
    public int maxProduct(int[] A) {
        //01:42
        if(A.length == 0) return 0;
        if(A.length == 1) return A[0];
        
        int maxLocal =  A[0];
        int minLocal = A[0];
        int maxGlobal = A[0];
        
        for(int i = 1; i < A.length; i++){
            int maxCopy = maxLocal;
            maxLocal = Math.max(Math.max(A[i], A[i] * maxLocal), A[i] * minLocal);
            minLocal = Math.min(Math.min(A[i], A[i] * maxCopy), A[i] * minLocal);
            maxGlobal = Math.max(maxGlobal, maxLocal);
        }
        return maxGlobal;
        //01:47
    }
}


LeetCode Maximum Product Subarray

标签:style   blog   http   io   ar   color   os   sp   java   

原文地址:http://blog.csdn.net/yangliuy/article/details/41590287

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