leetcode刷题系列--152. Maximum Product Subarray

来源:互联网 发布:js获取下拉框选中的值 编辑:程序博客网 时间:2024/06/15 06:16

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.

Subscribe to see which companies asked this question

Show Tags
Show Similar Problems
Have you met this question in a real interview? 
Yes
 
class Solution {public:    int maxProduct(vector<int>& nums) {        int len = nums.size();        if(len == 0)            return 0;        int pos_max = nums[0];        int neg_max = nums[0];        int res_max = nums[0];        for(int i = 1; i < len; ++i)        {            int a = pos_max * nums[i];            int b = neg_max * nums[i];            pos_max = max(max(a,b),nums[i]);            neg_max = min(min(a,b),nums[i]);            res_max = max(res_max,pos_max);        }        return res_max;    }};



特殊情况是

[2,-5,-2,-4,3]  如果从头开始遍历  那么是2 -5 -2  变成了20  再弄后面就不对了  其实应该是-2 -4 3  最大值是24

0 0
原创粉丝点击