首页 > 其他 > 详细

Maximum Product Subarray

时间:2015-03-17 17:27:38      阅读:146      评论: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.

 

依旧是DP算法,由于负数乘以负数也可以变成一个很大的数,因此要维护2个局部最优变量,局部最大和局部最小,代码如下:

public class Solution {
    
    public int Min(int a,int b) {
        return a<b?a:b;
    }
    
    public int Max(int a,int b) {
        return a>b?a:b;
    }
    
    public int maxProduct(int[] A) {
        int size = A.length;
        int local_max = A[0];//局部最大
        int local_min = A[0];//局部最小
        int global = A[0];//全局最大
        for(int i=1;i<size;i++) {
            int tmp = local_max;
            local_max = Max(Max(local_max*A[i],A[i]),local_min*A[i]);
            local_min = Min(Min(tmp*A[i],A[i]),local_min*A[i]);
            global = Max(global,local_max);
        }
        return global;
    }
}

 

Maximum Product Subarray

原文:http://www.cnblogs.com/mrpod2g/p/4344552.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!