LeetCode·152. Maximum Product Subarray

题目:

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.

思路:

  1. 动态规划;
  2. 保留上次计算的结果,包括最大值和最小值;
  3. 写出动态转移方程(见代码);

代码:

我的解法:

class Solution {
public:
    int maxProduct(vector<int>& nums) {
        if(nums.size() < 1)return 0;
        int pre_maxs = nums[0];
        int pre_mins = nums[0];
        int g_max = nums[0];

        for(int i = 1; i < nums.size(); ++i){
            int max_c = pre_maxs;
            pre_maxs = max(pre_mins*nums[i], max(nums[i], nums[i]*pre_maxs));
            pre_mins = min(max_c*nums[i], min(nums[i], nums[i]*pre_mins));
            if(g_max < pre_maxs)
                g_max = pre_maxs;
        }

        return g_max;
    }
};

最优解法:

class Solution {
public:
    int maxProduct(vector<int>& a) {

        int l = a.size();

        int maxval = a[0];
        int minval = a[0];
        int ans = a[0];

        for(int i=1;iif(a[i]<0)
                swap(maxval,minval);

            maxval = max(a[i],maxval*a[i]);
            minval = min(a[i],minval*a[i]);

            ans = max(ans,maxval);
        }
        return ans;
    }
};

结果:


LeetCode·152. Maximum Product Subarray_第1张图片

你可能感兴趣的:(Informal,essay)