Maximum Product Subarray

Leetcode又更新了


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.

找连续子数组,它们的乘积最大


思路:

维护两个数组pos和neg,一个记录正数的最大值,类似于max sub array sum,另一个维护负数的最小值

这样在遍历到某个数时,如果该数是正数,则用pos来更新pos,用neg来更新neg;如果该数是负数,则用pos来更新neg,用neg来更新pos

最后选pos中最大的即可

如果只有一个元素,直接返回该元素即可


class Solution {
public:
    int maxProduct(int A[], int n) {
        int *pos = new int[n];
        int *neg = new int[n];
        if(n==1)
            return A[0];
        pos[0] = 0;
        neg[0] = 0;
        if(A[0]>0){
            pos[0] = A[0];
        }else
            neg[0] =  A[0];
        for(int i=1;i<n;i++){
            if(A[i]>0){
                pos[i] = max(A[i],pos[i-1]*A[i]);
                neg[i] = neg[i-1]*A[i];
            }else{
                neg[i] = min(A[i],pos[i-1]*A[i]);
                pos[i] = neg[i-1]*A[i];
            }
        }
        int ma = -10000;
        for(int i=0;i<n;i++)
            ma = max(ma,pos[i]);
        return ma;
    }
};


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值