152. Maximum Product Subarray

欢迎fork and star:Nowcoder-Repository-github

152. Maximum Product Subarray

题目

 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. 

解析

  • 而对于Product Subarray,要考虑到一种特殊情况,即负数和负数相乘:如果前面得到一个较小的负数,和后面一个较大的负数相乘,得到的反而是一个较大的数,如{2,-3,-7},所以,我们在处理乘法的时候,除了需要维护一个局部最大值,同时还要维护一个局部最小值,由此,可以写出如下的转移方程式:
max_copy[i] = max_local[i]
max_local[i + 1] = Max(Max(max_local[i] * A[i], A[i]),  min_local * A[i])
min_local[i + 1] = Min(Min(max_copy[i] * A[i], A[i]),  min_local * A[i])
class Solution_152 {

    //分析:此题我们不仅要保存一个最大值,还得保存一个最小值,因为负负相乘等于正数,比如 - 2 4 - 5,即localMIn[i]表示以i结尾的连续字串乘积的最小值,而localMax[i]表示以i结尾的连续字串乘积的最大值,那么:
    //localMax[i] = max(max(localMin[i] * A[i], A[i] * localMax[i]), A[i]); 而localMin[i] = min(min(localMin[i] * A[i], A[i] * localMax[i]), A[i]);
public:
    int getMax(int x, int y)
    {
        return x > y ? x : y;
    }
    int getMin(int x, int y)
    {
        return x < y ? x : y;
    }
    int maxProduct(vector<int>& nums) {
        if (nums.size()==0)
        {
            return 0;
        }
        if (nums.size()==1)
        {
            return nums[0];
        }

        int local_min = nums[0];
        int local_max = nums[0];

        int global = nums[0];
        int local_max_copy = 0;
        for (size_t i = 1; i < nums.size(); i++)
        {
            local_max_copy = local_max;
            local_max = getMax(getMax(local_max*nums[i], nums[i]), local_min*nums[i]); //取三者中的大者
            local_min = getMin(getMin(local_min*nums[i], nums[i]),local_max_copy*nums[i]);
            global = getMax(global, local_max);

        }

        return global;
    }
};

题目来源

    原文作者:ranjiewen
    原文地址: https://www.cnblogs.com/ranjiewen/p/8136135.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞