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.
解题思路
这道题和之前所做的求各元素相加和最大的数组子序列的解法相近,都是使用了动态规划算法。但不同的是,乘法子序列的最大结果会在以下两种情况中产生:前面累乘得到的最大值的子序列与当前元素(正数)相乘、前面累乘得到的最小值与当前元素(负数)相乘。因此我们需要维护三个值,一个记录前面子序列累乘的得到的最大值,一个记录前面子序列累乘的得到的最小值,还有一个全局最大值。
各个数值的确定方法:
局部最小值:最大值 * 当前元素、最小值 * 当前元素、当前元素 三者中的最小值
局部最大值:最大值 * 当前元素、最小值 * 当前元素、当前元素 三者中的最大值
全局最大值:局部最大值中的最大值
C++代码
class Solution {
public:
int maxProduct(vector<int>& nums) {
int min_local, max_local, Max;
if(nums.size() == 1)
return nums[0];
min_local = nums[0];
max_local = nums[0];
Max = nums[0];
for(int i = 1; i < nums.size(); i++) {
int a = max_local*nums[i],
b = min_local*nums[i];
max_local = max(max(a, b), nums[i]);
min_local = min(min(a, b), nums[i]);
Max = max(Max, max_local);
}
return Max;
}
};