码迷,mamicode.com
首页 > 其他好文 > 详细

152. Maximum Product Subarray

时间:2019-02-15 01:05:13      阅读:201      评论:0      收藏:0      [点我收藏+]

标签:math   step   ber   one   imu   next   product   output   div   

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

标签:math   step   ber   one   imu   next   product   output   div   

原文地址:https://www.cnblogs.com/ruruozhenhao/p/10381307.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!