[LeetCode]Maximum Product Subarray
Maximum Product Subarray
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
.
还是动态规划的问题,由于负数的存在,这儿要维护3个变量,local_min,local_max,global。思路可以参考博客。
DP问题的关键是写出递推公式。
1 int copy_max = local_max; 2 local_max = max(max(local_max*nums[i],local_min*nums[i]),nums[i]); 3 local_min = min(min(local_min*nums[i],copy_max*nums[i]),nums[i]); 4 global = max(global,local_max);
这就是这道题的递推公式。
1 class Solution { 2 public: 3 int maxProduct(vector<int>& nums) { 4 if(nums.size()==0) return 0; 5 int global=nums[0],local_min=nums[0],local_max=nums[0]; 6 for(int i=1;i<nums.size();i++) 7 { 8 int copy_max = local_max; 9 local_max = max(max(local_max*nums[i],local_min*nums[i]),nums[i]); 10 local_min = min(min(local_min*nums[i],copy_max*nums[i]),nums[i]); 11 global = max(global,local_max); 12 } 13 return global; 14 } 15 };