152. Maximum Product Subarray

最大子段乘积,我会最大子段和,但是这道题我不会用DP做,呜呜呜呜(我还有救吗)。

我用的方法比较简单暴力,时间复杂度O(n*n),最终OJ测试通过是356ms(其实还可以哈

遍历数组,当前数为正数时直接乘同时更新最大值;为0时则置1;为负数时,需要先判断在 剩下的数组元素且在0元素之前 的负数的个数,若不再有负数则置1,若有偶数个则一直连乘到除最后一个负数,若有奇数个则连乘到最后一个元素,最后更新最大值,同时将临时最大值置1

PS:这道题的数组元素都是整数,若是有-1~1之间的小数,我这个解法就不能用了QAQ,动归的那个解法依旧适用

题目:

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.
class Solution {
public:
    int maxProduct(vector<int>& nums) {
        int maxP = -1e9;
        
        int p = 1;
        int len = nums.size();
        for(int i = 0; i < len; i++)
        {
            if(nums[i] > 0)
            {
                p *= nums[i];
                maxP = max(maxP, p);
            }
            else if(nums[i] == 0)
            {
                maxP = max(maxP, 0);
                p = 1;
            }
            else
            {
                int cnt0 = 0, j, jj;
                int pp = p;
                for(j = i + 1; j < len; j++)
                {
                    if(nums[j] < 0) 
                    {
                        cnt0++;
                        jj = j;
                    }
                    else if(nums[j] == 0)   break;
                }
                if(cnt0 == 0)
                {  
                    maxP = max(maxP, nums[i]);
                    p = 1;
                    continue;
                }
                else if(cnt0 % 2 == 0) jj = jj - 1;
                else    jj = j - 1;
                for(int k = i; k <= jj; k++)
                    pp *= nums[k];
                maxP = max(maxP, pp);
                p = 1;
            }
        }
        
        return maxP;
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值