https://leetcode-cn.com/problems/maximum-product-subarray/
题目描述给你一个整数数组 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-位 整数关键点
- 需要记录 左边最大 和最小数
- 遇到零值 则重置为 0
- 语言支持:Java
Java Code:
class Solution {
public int maxProduct(int[] nums) {
int res = nums[0];
int max = nums[0];
int min = nums[0];
for(int i=1;i
int tmp = max;
max = Math.max( Math.max(nums[i] * min , nums[i] * tmp ), nums[i]);
min = Math.min( Math.min(nums[i] * min , nums[i] * tmp ), nums[i]);
res = Math.max(res,max);
}
return res;
}
}
复杂度分析
令 n 为数组长度。
- 时间复杂度: O ( n ) O(n) O(n)
- 空间复杂度: O ( n ) O(n) O(n)



