【题目】
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.
【思路】
这是一道DP题目,考虑到当两个负数相乘为正这个因素,所以需要额外考虑局部最小值这个因素,得到状态转换方程为:
max(i) = Max(Max(max(i-1) * nums[i], min(i-1) * nums[i]), nums[i])
min(i) = Min(Min(max(i-1) * nums[i], min(i-1) * nums[i]), nums[i])
global = Max(global, max(i))
【c++代码】
class Solution {
public:
int max_local, min_local, global;
vector<int> numbers;
int maxProduct(vector<int>& nums) {
numbers = nums;
max(numbers.size() - 1);
return global;
}
void max(int i)
{
int a, b, c;
if (i == 0)
{
max_local = min_local = global = numbers[0];
} else
{
max(i - 1);
c = numbers[i];
a = max_local * c;
b = min_local * c;
max_local = (a > b) ? (a > c ? a : c):(b > c ? b : c);
min_local = (a < b) ? (a < c ? a : c):(b < c ? b : c);
global = max_local >= global ? max_local:global;
}
}
};