46.Maximum Product Subarray(最大乘积子数组)
Level:
Medium
题目描述:
Given an integer array nums
, find the contiguous subarray within an array (containing at least one number) which has the largest product.
Example 1:
Input: [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.
Example 2:
Input: [-2,0,-1]
Output: 0
Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
思路分析:
因为是乘积的最大值,可能是若干个正数相乘得到,也可能是若干个负数相乘得到;因此,必须保留前一阶段的最大值和最小值k+1在内结尾的最小乘积序列为:
min(k+1) = min(min(k) * a[k+1], max(k) * a[k+1], a[k+1])
代码:
public class Solution{
public int maxProduct(int []nums){
int dp=nums[0];
int maxk=nums[0]; //第K阶段的最大值
int mink=nums[0]; //第K阶段的最小值
int maxcur=maxk;
int mincur=mink;
for(int i=1;i<nums.length;i++){
maxk=Math.max(Math.max(maxcur*nums[i],mincur*nums[i]),nums[i]);
mink=Math.min(Math.min(maxcur*nums[i],mincur*nums[i]),nums[i]);
maxcur=maxk;
mincur=mink;
dp=Math.max(dp,maxcur);
}
return dp;
}
}