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- i的累乘结果,肯定为最大值,如果当前累乘为负数,
则最大值从第一个负数后面的第一个数开始累乘到当前下标的积,则只要记录当前第一个累乘为负数的积,
当前累乘积 / 第一个负数 即为最大累乘结果!用divid表示第一个负数的累乘积,在未出现负数先,divid= 1;
表示从左到右开始累乘。
现在考虑有0的情况,当遇到0时,左边的值按上述计算即可,右边的最大值,按从右边第一个开始计算即可,
则最大值肯定为max{0, 左最大,右最大};因为若包括0,则积为0, 不包括则只需考虑左右即可!
class Solution {
public:
int maxProduct(int A[], int n) {
if(n <= 0)return 0;
for(int i = 1; i < n; i++)
if(A[i - 1])A[i] *= A[i - 1];//若a[i - 1] == 0 最大积肯定为max{0,两边的积的最大值},右边从0第一个算
int divid = 1;
int maxMtp = INT_MIN;
for(int i = 0; i < n; i++)
{
if(A[i] < 0)//若当前积小于0 则最大值为当前积除以 第一个负数积
maxMtp = max(maxMtp, A[i] / divid);
else maxMtp = max(maxMtp, A[i]);//当前为正数,则直接与当前最大值比较
if(A[i] < 0 && divid == 1)divid = A[i];//divid指向第一个负数的积
if(!A[i])divid = 1;//若A[i]为0 ,则当前最大值和,0右边的最大值比,所有divid置为1
}
return maxMtp;
}
};