152. 乘积最大子数组
中等
给你一个整数数组 nums
,请你找出数组中乘积最大的非空连续子数组(该子数组中至少包含一个数字),并返回该子数组所对应的乘积。
测试用例的答案是一个 32-位 整数。
子数组 是数组的连续子序列。
示例 1:
输入: nums = [2,3,-2,4]
输出: 6
解释: 子数组 [2,3] 有最大乘积 6。
示例 2:
输入: nums = [-2,0,-1]
输出: 0
解释: 结果不能为 2, 因为 [-2,-1] 不是子数组。
提示:
1 <= nums.length <= 2 * 104
-10 <= nums[i] <= 10
nums
的任何前缀或后缀的乘积都 保证 是一个 32-位 整数
动态规划
https://leetcode.cn/problems/maximum-product-subarray/solutions/10127/c-su-du-100nei-cun-92li-yong-zui-da-zhi-he-fu-zui-/
class Solution {
/**
利用最大值和负最大值求解:
由于乘法的特殊性,所以string上每一位的乘积最大值(不论正负),
都只与前一个值能达到的最大值(当前数字为正)和最小值(当前数位为负)有关系。
所以,只存储上一位的最大和最小可能乘积,然后计算并储存,
计算后比较该数位最大值与之前所有数位的最大可能出现的乘积,记录。
*/
public int maxProduct(int[] nums) {
int n = nums.length;
if(n == 1) return nums[0];
int pos = nums[0], neg = nums[0], ret = nums[0];
for(int i = 1; i < n; i++){
int tmp = pos;
pos = Math.max(nums[i], Math.max(pos * nums[i], neg * nums[i]));
neg = Math.min(nums[i], Math.min(tmp * nums[i], neg * nums[i]));
ret = Math.max(ret, pos);
}
return ret;
}
}