- 1.题目
- 2.思路
- 3.代码实现(Java)
给你一个整数数组 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-位 整数
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/maximum-product-subarray
(1)暴力穷举法
(2)动态规划
思路参考本题官方题解。
//思路1————暴力穷举法
public int maxProduct(int[] nums) {
//res 保存乘积最大子数组所对应的乘积,初始值为 Integer.MIN_VALUE
int res = Integer.MIN_VALUE;
int length = nums.length;
//循环穷举所有的子数组,并用 res 保存乘积最大子数组所对应的乘积
for (int i = 0; i < length; i++) {
int tmp = nums[i];
res = Math.max(res, nums[i]);
for (int j = i + 1; j < length; j++) {
tmp *= nums[j];
res = Math.max(res, tmp);
}
}
return res;
}
//思路2————动态规划
public int maxProduct(int[] nums) {
int res = Integer.MIN_VALUE;
int length = nums.length;
int[] maxF = new int[length];
int[] minF = new int[length];
System.arraycopy(nums, 0, maxF, 0, length);
System.arraycopy(nums, 0, minF, 0, length);
for (int i = 1; i < length; i++) {
maxF[i] = Math.max(maxF[i - 1] * nums[i], Math.max(nums[i], minF[i - 1] * nums[i]));
minF[i] = Math.min(minF[i - 1] * nums[i], Math.min(nums[i], maxF[i - 1] * nums[i]));
}
res = maxF[0];
for (int i = 1; i < length; i++) {
res = Math.max(res, maxF[i]);
}
return res;
}



