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
.
动态规划最重要的是写出转移方程
class Solution {
public:
int maxProduct(vector<int>& nums) {
if(nums.size() == 1)return nums[0];
int dpmin = nums[0];
int dpmax = nums[0];
int resmax= dpmax;
for(int i = 1; i < nums.size(); i++){
int mx = dpmax * nums[i];
int mn = dpmin * nums[i];
dpmax = max(max(mn, mx), nums[i]);
dpmin = min(min(mn, mx), nums[i]);
resmax = max(dpmax, resmax);
}
return resmax;
}
};