152. Maximum Product Subarray

Posted ruruozhenhao

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了152. Maximum Product Subarray相关的知识,希望对你有一定的参考价值。

Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.

Example 1:

Input: [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.

Example 2:

Input: [-2,0,-1]
Output: 0
Explanation: The result cannot be 2, because [-2,-1] is not a subarray.

 

Approach #1: Math. [C++]

class Solution {
public:
    int maxProduct(vector<int>& nums) {
        int size = nums.size();
        if (size == 0) return size;
        
        int ans = nums[0];
        int curmax = nums[0];
        int curmin = nums[0];
        for (int i = 1; i < size; ++i) {
            int nextmax = curmax * nums[i];
            int nextmin = curmin * nums[i];
            curmax = max(nums[i], max(nextmax, nextmin));
            curmin = min(nums[i], min(nextmax, nextmin));
            ans = max(ans, max(curmax, curmin));
        }
        
        return ans;
    }
};

  

Analysis:

Because nums is an integer array, so nums[i] > 1.  In this travel‘s every step(++i) we find the curmin and curmax and ans from 0 to current index(i), curmin can become curmax and curmax can become curmin, if both curmin and curmax are less than 0, nums[i] > 0 so nums[i] is the curmax.

 

以上是关于152. Maximum Product Subarray的主要内容,如果未能解决你的问题,请参考以下文章

152. Maximum Product Subarray(js)

152. Maximum Product Subarray

leetcode 152. Maximum Product Subarray

刷题152. Maximum Product Subarray

LeetCode 152. Maximum Product Subarray

152. Maximum Product Subarray