Leetcode又更新了
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
.
思路:
维护两个数组pos和neg,一个记录正数的最大值,类似于max sub array sum,另一个维护负数的最小值
这样在遍历到某个数时,如果该数是正数,则用pos来更新pos,用neg来更新neg;如果该数是负数,则用pos来更新neg,用neg来更新pos
最后选pos中最大的即可
如果只有一个元素,直接返回该元素即可
class Solution {
public:
int maxProduct(int A[], int n) {
int *pos = new int[n];
int *neg = new int[n];
if(n==1)
return A[0];
pos[0] = 0;
neg[0] = 0;
if(A[0]>0){
pos[0] = A[0];
}else
neg[0] = A[0];
for(int i=1;i<n;i++){
if(A[i]>0){
pos[i] = max(A[i],pos[i-1]*A[i]);
neg[i] = neg[i-1]*A[i];
}else{
neg[i] = min(A[i],pos[i-1]*A[i]);
pos[i] = neg[i-1]*A[i];
}
}
int ma = -10000;
for(int i=0;i<n;i++)
ma = max(ma,pos[i]);
return ma;
}
};