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
.
思路:使用动态规划,维护两个变量,一个正数的最大值pmax,一个负数的最大值pmin。
class Solution {
public:
int maxProduct(int A[], int n) {
int pmax = A[0],pmin = A[0],ans = A[0];
for(int i = 1;i < n;i ++){
int tmax = A[i] * pmax;
int tmin = A[i] * pmin;
pmax = max(A[i],max(tmax,tmin));
pmin = min(A[i],min(tmax,tmin));
ans = max(ans,pmax);
}
return ans;
}
};