【LeetCode】152. Maximum Product Subarray

题目:

Find the contiguous subarray within an array (containing at least one number) which has the largest product.post

For example, given the array [2,3,-2,4],spa

the contiguous subarray [2,3] has the largest product = 6.code

提示:

这道题能够使用动态规划求解,可是因为是乘法运算,因此状况更加复杂。联想乘法运算的性质:两个负数相乘获得一个正数,也就是说咱们在计算过程当中,若是产生了一个很大的负数,以后又遇到了一个负数,那么其乘积就会变成正数,进而可能成为潜在的答案。所以,咱们建立两个变量,分别记录运算过程当中的最大值和最小值。另外,当遇到负数时,把这两个变量进行交换(由于那个最小值乘以负数以后就会成为最大值)。具体看下列代码:blog

代码:

class Solution {
public:
    int maxProduct(vector<int>& nums) {
        if (nums.empty()) {
            return 0;
        }
        int res = nums[0];
        for (int i = 1, imax = res, imin = res; i < nums.size(); ++i) {
            if (nums[i] < 0) {
                swap(imax, imin);
            }
            // 幸运的是,这样的作法对数值0也一样有效
            imax = max(nums[i], imax * nums[i]);
            imin = min(nums[i], imin * nums[i]);
            res = max(res, imax);
        }
        return res;
    }
};
相关文章
相关标签/搜索