友情支持
如果您觉得这个笔记对您有所帮助,看在D瓜哥码这么多字的辛苦上,请友情支持一下,D瓜哥感激不尽,😜
|
|
有些打赏的朋友希望可以加个好友,欢迎关注D 瓜哥的微信公众号,这样就可以通过公众号的回复直接给我发信息。

公众号的微信号是: jikerizhi。因为众所周知的原因,有时图片加载不出来。 如果图片加载不出来可以直接通过搜索微信号来查找我的公众号。 |
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-位 整数
思路分析
53. 最大子数组和 与本题思路类似。但是,这道题要同时维护连续最大乘积和连续最小乘积(负负得正)。
-
一刷
-
二刷
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
* Runtime: 1 ms, faster than 97.91% of Java online submissions for Maximum Product Subarray.
*
* Memory Usage: 36.4 MB, less than 100.00% of Java online submissions for Maximum Product Subarray.
*
* Copy form: https://leetcode.com/problems/maximum-product-subarray/discuss/48230/Possibly-simplest-solution-with-O(n)-time-complexity[Possibly simplest solution with O(n) time complexity - LeetCode Discuss]
*/
public int maxProduct(int[] nums) {
// store the result that is the max we have found so far
int result = nums[0];
// max/min stores the max/min product of
// subarray that ends with the current number nums[i]
for (int i = 1, max = result, min = result; i < nums.length; i++) {
// multiplied by a negative makes big number smaller, small number bigger
// so we redefine the extremums by swapping them
if (nums[i] < 0) {
int temp = max;
max = min;
min = temp;
}
// max/min product for the current number is either the current number itself
// or the max/min by the previous number times the current one
min = Math.min(nums[i], min * nums[i]);
max = Math.max(nums[i], max * nums[i]);
// the newly computed max value is a candidate for our global result
result = Math.max(result, max);
}
return result;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
* @author D瓜哥 · https://www.diguage.com
* @since 2025-11-02 11:10:11
*/
public int maxProduct(int[] nums) {
int[] maxDp = new int[nums.length];
int[] minDp = new int[nums.length];
maxDp[0] = nums[0];
minDp[0] = nums[0];
int result = nums[0];
for (int i = 1; i < nums.length; i++) {
minDp[i] = Math.min(Math.min(nums[i], minDp[i - 1] * nums[i]), maxDp[i - 1] * nums[i]);
maxDp[i] = Math.max(Math.max(nums[i], maxDp[i - 1] * nums[i]), minDp[i - 1] * nums[i]);
result = Math.max(result, maxDp[i]);
}
return result;
}

