152. Maximum Product Subarray
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
.
在数组中找到子阵(至少包含一个数字)具有最大。
例如,给定的数组[ 2,3 - 4 ],
的子阵[ 2,3 ]拥有最大= 6。
首先要先弄懂题目的意思就是根据数组得到一个最大的数,这是提供的数组得出一个最大结果
class Solution {
int maxProduct(int A[], int n) {
int frontProduct = 1;
int backProduct = 1;
int ans = INT_MIN;
for (int i = 0; i < n; ++i) {
frontProduct *= A[i];
backProduct *= A[n - i - 1];
ans = max(ans,max(frontProduct,backProduct));
frontProduct = frontProduct == 0 ? 1 : frontProduct;
backProduct = backProduct == 0 ? 1 : backProduct;
}
return ans;
}
};