给你一个整数数组 nums ,请你找出数组中乘积最大的连续子数组(该子数组中至少包含一个数字),并返回该子数组所对应的乘积。
示例 1:
输入: [2,3,-2,4]
输出: 6
解释: 子数组 [2,3] 有最大乘积 6。
示例 2:
输入: [-2,0,-1]
输出: 0
解释: 结果不能为 2, 因为 [-2,-1] 不是子数组。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximum-product-subarray
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
方法一:暴力
class Solution {
public int maxProduct(int[] nums) {
int ans = Integer.MIN_VALUE;
int mul = 1;
for(int i = 0; i < nums.length; i++) {
mul = 1;
for(int j = i; j >= 0; j--) {
mul *= nums[j];
ans = Math.max(ans, mul);
}
}
return ans;
}
}
方法二:动态规划
dp含义:以第i个数为结尾的子序列的最大乘积
状态转移方程:max{dp[i-1]*nums[i],nums[i]};
这题不同点:数据中有负数,因为有负负得正,所以我们还需要记录到目前截止这个数的最小乘积,当当前这个数是负数的时候,最大乘以这个数会变成负的,最小的乘以这个数就变成正的,所以在相乘之前,我们需要将max和min交换位置。
class Solution {
public int maxProduct(int[] nums) {
int max = 1;
int min = 1;
int ans = Integer.MIN_VALUE;
for(int i = 0; i < nums.length; i++) {
if(nums[i] < 0) {//交换
int temp = max;
max = min;
min = temp;
}
max = Math.max(max*nums[i], nums[i]);
min = Math.min(min*nums[i], nums[i]);
ans = Math.max(ans, max);
}
return ans;
}
}