Leetcode:Maximum Product Subarray

连接:https://leetcode.com/problems/maximum-product-subarray/#/description

题意: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.

思路:

整体的思路就是动态规划,left[i]为从开始到i的位置乘积数值,right[i]表示从结尾到i的位置乘积数值。最终的结果是:
max = Max{left[i],right[i],left[i]*right[i+1]};
其中值得注意的问题是:

  • left[i]如果为负数,且{i+1,…,size-1}的位置没有负数,则后面的数字相乘并不会把结果变成正数,所以此时需要把left[i]的值变成1.所以我们用leftNge[i]存储从开始位置到i位置有多少个负数。
  • nums[]中可能会出现0的数值,例如nums[i]==0,则left[i]=nums[i]*left[i-1]; left[i]==0,之后的如何left[i…size]恒等于0,所以若出现0的情况,则直接将left[i]=nums[i];rigth[]和rightNge[]的表示从结尾到位置i,原理基本一样。

代码如下:


public class Solution {

        public int maxProduct(int[] nums) {
        int max = nums[0];
        int size = nums.length;
        int[] left = new int[size];
        int[] leftNge = new int[size];

        int[] right = new int[size];
        int[] rightNge = new int[size];
        left[0] = nums[0];
        right[size-1] = nums[size-1];
        if(nums[0]<0)
            leftNge[0]=1;
        if(nums[size-1]<0){
            rightNge[size-1]=1;
        }
        for(int i=1;i<size;i++){
            if(nums[i]<0)
                leftNge[i]=leftNge[i-1]+1;
            else
                leftNge[i]=leftNge[i-1];
        }
        for(int i=size-2;i>=0;i--){
            if(nums[i]<0)
                rightNge[i]=rightNge[i+1]+1;
            else
                rightNge[i]=rightNge[i+1];
        }
        for(int i=1;i<size-1;i++){
            if(left[i-1]==0){
                left[i] = nums[i];
            }else{
                left[i]=nums[i]*left[i-1];
                if(left[i]<0&&rightNge[i+1]==0){
                    left[i]=1;
                }
            }
        }

        for(int i=size-2;i>=1;i--){
            if(right[i+1]==0){
                right[i] = nums[i];
            }else{
                right[i]=nums[i]*right[i+1];
                if(right[i]<0&&left[i-1]==0)
                    right[i] = 1;
            }
        }
        for(int i=0;i<size-1;i++){
            int temp = left[i]*right[i+1];
            max = Math.max(temp,max);
            max = Math.max(left[i],max);
            max = Math.max(right[i+1],max);
        }
        return max;
    }
}

运行结果:
这里写图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值