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.
给出一个数组,求其中子数组的最大积,子数组必须是连续的。
思路:
求最大积和最大和的区别是,最大和只需要保存当前最大值就行,但是最大积还需要保存最小值,因为负数乘负数可以得到正数,
比如[-2, 3, -4]
走到3的时候最大是3,最小是-6,但是走到-4的时候,最大值就会由(-6)乘(-4)得来
所以要保存当前最大值,当前最小值和到目前为止的最大乘积,最后直接返回最大乘积就行。
当前最大值是以下3种的max
前一次最大值 * 当前值
前一次最小值 * 当前值
当前值
同理,当前最小值是以下3种的min
前一次最大值 * 当前值
前一次最小值 * 当前值
当前值
而当前最大乘积是以下两种的max
上面求到的当前最大值
当前值
int maxProduct(vector<int>& nums) {
vector<int> max_current(nums.size(), 0);
vector<int> min_current(nums.size(), 0);
int max_product = nums[0];
max_current[0] = nums[0];
min_current[0] = nums[0];
for (int i = 1; i < nums.size(); i++) {
int cur_max = nums[i] * max_current[i - 1];
int cur_min = nums[i] * min_current[i - 1];
max_current[i] = max(nums[i], max(cur_max, cur_min));
min_current[i] = min(nums[i], min(cur_max, cur_min));
max_product = max(max_current[i], max_product);
}
return max_product;
}