Description
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.
Solution 1(C++)
class Solution {
public:
int maxProduct(vector<int>& nums) {
int len=nums.size();
int res=nums[0];
int curmax=res, curmin=res;
for(int i=1; i<len; i++){
if(nums[i]<0) swap(curmax, curmin);
curmax=max(nums[i], curmax*nums[i]);
curmin=min(nums[i], curmin*nums[i]);
res=max(res, curmax);
}
return res;
}
};
算法分析
由于这里要计算的是连续数列的乘积,同时,考虑到数列中有正数与负数。如果数列中不存在0,那么,很简单,我们只要把按照数列中元素的顺序一个个乘起来,然后同时计算最大值与最小值,如果有负数出现,就相当于提前乘以一个-1。最大值与最小值的数值将替换。但是现在数列中有可能有0。所以用动态规划的方法思考,无非就是有两种可能,nums[i]与curmax * nums[i],或者nums[i], curmin * nums[i]。所以用动态规划的方法,获取当前curmax与curmin。然后在res与curmax中取较大值即可。
程序分析
略。