152. Maximum Product Subarray
- Total Accepted: 65740
- Total Submissions: 286731
- Difficulty: Medium
Find the contiguous subarray within an array (containing at least one number) which has the largest product.
For example, given the array [2,3,-2,4]
,
the contiguous subarray [2,3]
has the largest product = 6
.
思路:DP。注意到乘积变化的连续性,设nums[i]所在子序列的最大值为Smax[i],nums[i]所在子序列的最小值为Smin[i]。
那么有
1. Smax[i]=max(Smax[i]*nums[i-1],Smin[i]*nums[i-1],nums[i]);
2. Smin[i]=min(Smax[i]*nums[i-1],Smin[i]*nums[i-1],nums[i])。
所以,result=max(Smax[0]...Smax[n-1])。
代码:
1 class Solution { 2 public: 3 int maxProduct(vector<int>& nums) { 4 int result=nums[0],maxproduct=nums[0],minproduct=nums[0],i,n=nums.size(); 5 for(i=1;i<n;i++){ 6 int temp=maxproduct; 7 maxproduct=max(max(maxproduct*nums[i],minproduct*nums[i]),nums[i]); 8 minproduct=min(min(temp*nums[i],minproduct*nums[i]),nums[i]); 9 result=max(maxproduct,result); 10 } 11 return result; 12 } 13 };