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

Maximum Product Subarray

时间:2015-03-17 17:30:40      阅读:159      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!