leetcode 152. Maximum Product Subarray

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.

思路:

本题和剑指offer:求连续子数组的最大和https://blog.csdn.net/orangefly0214/article/details/85628042是一样的思路,不过求和的时候比较简单,累加后变大了,则继续累加,变小了则从当前数开始。但是这个累乘就不太一样,我按照原来的思路写了第一版代码,然后很多case都没通过。

看完case,发现是因为没有考虑负数的缘故,累乘有两种情况:

1.累乘结果的最大值累乘一个正数,值变大。

2.累乘结果的最小值累乘一个负数,值也会变大。

所以我们不能按加法时只保存当下的最大值,而应该将最大值和最小值都保存下来。

 

另,暴力求解的话,用两个for循环遍历,保留累乘的最大值即可。

实现1:

class Solution {
    public int maxProduct(int[] nums) {
        int currMin=nums[0];
        int currMax=nums[0];
        int max=nums[0];
        for(int i=1;i<nums.length;i++){
            int t1=currMin*nums[i];
            int t2=currMax*nums[i];
            currMax=Math.max(Math.max(t1,t2),nums[i]);
            currMin=Math.min(Math.min(t1,t2),nums[i]);
            max=Math.max(currMax,max);
        }
        return max;
    }
}

实现2:

class Solution {
    public int maxProduct(int[] nums) {
       int max=nums[0];
       int prevMin = nums[0], prevMax = nums[0];
	   int curMin, curMax;
	   for (int i = 1; i < nums.length; ++i) {
		   curMin = Math.min(Math.min(prevMax * nums[i], prevMin * nums[i]), nums[i]);
		   curMax = Math.max(Math.max(prevMax * nums[i], prevMin * nums[i]), nums[i]);
		   prevMin = curMin;
		   prevMax = curMax;
		   max = Math.max(curMax, max);
		}
		return max;

    }
}

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值