152. Maximum Product Subarray

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

按0分成几段 每段最大值在这几个之间出 1.全乘起来 2.第一个负数及之前的除外 剩下的全乘起来 3.最后一个负数及之后的除外,剩下的全乘起来 然后再所有这些值里取最大的

public class Solution {
    public int maxProduct(int[] nums) {
        int ret = Integer.MIN_VALUE;
        if(nums.length==1)return nums[0];
        ret = nums[0];
        int i = 0;
        while(i<nums.length){
            int cheng1 = 1;
            int cheng2 = 1;
            int start = 0;//第一个负数之后开始乘
            while(i<nums.length&&nums[i]!=0){
                cheng1*=nums[i];
                if(start==1)cheng2*=nums[i];
                if(cheng1>ret)ret = cheng1;
                if(start==1&&cheng2>ret)ret=cheng2;
                if(nums[i]<0)start=1;
                i++;
            }
            if(i<nums.length&&nums[i]==0&&ret<0)ret=0;
            i++;
        }
        return ret;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值