第十五周LeetCode

题目
Maximum Product Subarray
难度 Medium

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.

实现思路

这个题跟Maximum Subarray很相似,但是因为乘积时负数乘负数得到整数,可能在乘上一个负数时得到最大值,因此不能只用一个数组做动态规划,需要分成最大值和最小值数组。但是我们可以用四个变量做动态规划,因为dp[i]只用到了dp[i-1],不需要存所有的数组,因此只用cur_max,pre_max,cur_min,pre_min存当前最大值,前一个最大值,当前最小值和前一个最小值。由于pre_min乘上nums[i]后,可能变成最大值,而pre_max乘上nums[i]之后可能变成最小值,因此cur_max和cur_min都取决于pre_max*nums[i],pre_min*nums[i]和nums[i]本身。最后求出最大的cur_max即为所求答案。

实现代码

int maxProduct(vector<int>& nums) {
        int cur_max = nums[0], pre_max = nums[0], ans = nums[0];
        int cur_min = nums[0], pre_min = nums[0];

        for (int i = 1; i < nums.size(); i++) {
            cur_min = min(min(pre_max*nums[i],pre_min*nums[i]),nums[i]);
            cur_max = max(max(pre_max*nums[i],pre_min*nums[i]),nums[i]);
            pre_max = cur_max;
            pre_min = cur_min;
            ans = max(cur_max, ans);
        }
        return ans;
    }

猜你喜欢

转载自blog.csdn.net/unirrrrr/article/details/78808023
今日推荐