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

LeetCode:Maximum Product Subarray

时间:2014-11-03 22:35:55      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:algorithm   leetcode   

题目描述:

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 Solution::maxProduct(int A[],int n)
{
    if(n == 1)
        return A[0];
    int max_temp = A[0];
    int min_temp = A[0];
    int result = A[0];
    int i;
    for(i = 1;i < n;i++)
    {
        int max_temp2 = max_temp * A[i];
        int min_temp2 = min_temp * A[i];
        max_temp = max(max_temp2,max(min_temp2,A[i]));
        min_temp = min(min_temp2,min(max_temp2,A[i]));
        if(max_temp > result)
            result = max_temp;
    }
    return result;
}


LeetCode:Maximum Product Subarray

标签:algorithm   leetcode   

原文地址:http://blog.csdn.net/yao_wust/article/details/40748013

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