給你一個整數數組 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;
}
}