题目
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
.
标签:Array、Dynamic Programming
相似题目: (M) Maximum Subarray, (E) House Robber, (M) Product of Array Except Self
题意
给定一个数组,找出数组中连续子串的乘积的最大值。
解题思路
很明显是一道动态规划的题目,那么就要确定局部最优解和全局最优解。局部最优解可以看做是历史乘积和历史乘积与当前数乘积的最大值,即local_max = Max(local_max,local_max * nums[i])
。但是这里需要考虑的是,如果一个local_max和一个数进行了乘积之后为一个很小的负数,但是下一次乘积时又乘上了一个负数,就变成了一个较大的整数。
考虑到以上情况之后,递推公式应该是:
copy_max = local_max
local_max = Max(Max(nums[i],local_max * nums[i]),local_min * nums[i])
local_min = Min(Min(nums[i],local_min * nums[i]),local_min * nums[i])
代码
class Solution {
public:
int maxProduct(vector<int>& nums) {
int n = nums.size();
if (n < 1) {
return 0;
}
int max_local = nums[0];
int min_local = nums[0];
int globel = nums[0];
for (int i = 1; i < n; i++) {
int max_copy = max_local;
max_local = max(max(nums[i],max_local * nums[i]), min_local * nums[i]);
min_local = min(min(nums[i],max_copy * nums[i]),min_local * nums[i]);
globel = max(globel, max_local);
}
return globel;
}
};