# 算法设计与分析（十四）

## Maximum Product Subarray

### 题目

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.

### 分析

s[j] = max(s[j-1] + a[j], a[j]);

max_cur[i] = max(nums[i-1], max((max_cur[i-1]*nums[i-1]), min_cur[i-1]*nums[i-1]));


min_cur[i] = min(nums[i-1], min(max_cur[i-1]*nums[i-1], min_cur[i-1]*nums[i-1]));


### 源码

class Solution {
public:
int maxProduct(vector<int>& nums) {
int size = nums.size();
int max1 = 0;
vector<int> max_cur(size + 1, 0);
vector<int> min_cur(size + 1, 0);
max_cur[0] = 1;
if(size >= 1) {
max_cur[1] = nums[0];
min_cur[1] = nums[0];
}
if(size == 1) {
return nums[0];
}
for(int i = 2; i <= size; i++) {
min_cur[i] = min(nums[i-1], min(max_cur[i-1]*nums[i-1], min_cur[i-1]*nums[i-1]));
max_cur[i] = max(nums[i-1], max((max_cur[i-1]*nums[i-1]), min_cur[i-1]*nums[i-1]));
}
for(int i = 1; i <= size; i++) {
if(max_cur[i] > max1) {
max1 = max_cur[i];
}
}
return max1;
}
};


10-17

09-23 5210
06-01 1万+
09-16 6211
11-04 7055
09-07 3408