xinyu04

导航

LeetCode 152 Maximum Product Subarray 思维

Given an integer array nums, find a contiguous non-empty subarray within the array that has the largest product, and return the product.

The test cases are generated so that the answer will fit in a 32-bit integer.

A subarray is a contiguous subsequence of the array.

Solution

求最大乘积的子区间。注意到数组不一定全是正数。但是我们可以分别求出前缀积以及后缀积来得到最大值。为什么?为什么区间一定是前缀或者后缀??

我们先不考虑 \(0\) 的情况,因为如果数组中有 \(0\) 的情况,这会使得区间乘积都变为0,所以我们只需从下个不为零的下标开始即可。

  • 如果数组全为正数,那么显然包括前后两个端点。
  • 如果数组中含有负数,且负数在中间,如果不选负数,那么同样是前后端点的区间;如果选取负数,我们同样可以选取偶数个负数使其变为正数,如果不能的话,则可以到负数前位置即可。不管那种情况,答案都是以前后两端的区间
  • 如果两头是负数;或者只有一端是负数,答案同样是前缀区间或者后缀区间,二者取 \(\max\) 即可
点击查看代码
class Solution {
private:
    int ans;
public:
    int maxProduct(vector<int>& nums) {
        int n = nums.size();
        if(n==1) return nums[0];
        int lmax=0, rmax=0; ans = nums[0];
        for(int i=0;i<n;i++){
            lmax = ((lmax==0)?1:lmax)*nums[i];
            rmax = ((rmax==0)?1:rmax)*nums[n-i-1];
            ans = max(ans,max(rmax,lmax));
           // cout<<ans<<endl;
        }
        return ans;
    }
};

posted on 2022-07-30 03:09  Blackzxy  阅读(13)  评论(0编辑  收藏  举报