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.

解法一:(双层遍历)

最简单粗暴的方法就是双层遍历。直接上代码:

public static int maxProduct(int[] nums) {
		int max = Integer.MIN_VALUE ;
		for(int low=0; low<nums.length; low++) {
			int temp = 1 ;
			for(int fast=low; fast<nums.length; fast++) {
				temp = temp * nums[fast] ;
				max = Integer.max(max, temp) ;
			}
			
		}
		return max ;
	}

解法二(最大值最小值一次遍历) :

上面的算法一开就达不到时间复杂度的要求。所以只能看看有没有更简单的方法。

可以通过一次遍历过程中,分别记录当前乘积的最大值和最小值。这里为什么要记录最小值?因为数组中可能存在一个或多个负数。如果当前累计的乘积值是负数,最大值是正数,那么极有可能因为接下来的一个数是负数,造成负负得正,一下超过了当前的最大值。当然,也有可能负负得正后依然没有超过当前最大值的可能性。所以总结下来,算法如下:

  1. 依次遍历数组的中的数字,并设max和min分别记录累计乘积过程中产生的最大值和最小值;max和min初始值即为数组的第一个元素值
  2. 找到max*nums[i], min*nums[i]和nums[i],三者中的最大值,并更新max
  3. 找到max*nums[i], min*nums[i]和nums[i],三者中的最小值,并更新min
  4. 数组遍历完成后,最后记录的max即为最大累计乘积
// Copy from: https://leetcode.com/problems/maximum-product-subarray/discuss/484927/My-java-O(n)-solution.	
public static int maxProduct(int[] nums) {
		if (nums.length < 1)
			return 0;
		int res = nums[0];
		int max = res, min = res;
		for (int i = 1; i < nums.length; i++) {
			int temp = max;
			max = Math.max(max * nums[i], Math.max(min * nums[i], nums[i]));
			min = Math.min(temp * nums[i], Math.min(min * nums[i], nums[i]));
			res = Math.max(res, max);
		}
		return res;
	}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yexianyi

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值