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
.
分析:若数组中没有0,若包含的负数个数为偶数,则为全部数组,如果是奇数,则是左边第一个负数右边的子数组以及右边第一个负数左边的子数组两者之间的最大值。若存在0,则可以根据0的位置将数组分解为没0的子数组进行求解
class Solution {
public:
void maxNum(int A[], int l, int r, int &ret)
{
if(l > r)return;
bool two = true;
int max = A[l];
int temp = 1;
for(int i = l; i <= r; i++)
{
temp *= A[i];
if(A[i] < 0)
two = !two;
if(two)
max = temp;
}
if(max > ret)
ret = max;
max = A[l];
two = true;
temp = 1;
for(int i = r; i >= l; i--)
{
temp *= A[i];
if(A[i] < 0)
two = !two;
if(two)
max = temp;
}
if(max > ret)
ret = max;
}
int maxProduct(int A[], int n) {
vector<int> zero;
int ret = A[0];
zero.push_back(-1);
for(int i = 0; i < n; i++)
{
if(!A[i])
zero.push_back(i);
}
zero.push_back(n);
int m = zero.size();
for(int i = 0; i < m-1; i++)
{
int l = zero[i]+1;
int r = zero[i+1]-1;
maxNum(A,l,r,ret);
}
if(ret < 0 && m > 2) ret = 0;
return ret;
}
};