题解 | #子数组最大乘积#
子数组最大乘积
http://www.nowcoder.com/practice/9c158345c867466293fc413cff570356
class Solution {
public:
double maxProduct(vector<double> arr) {
int n = arr.size();
if(arr.size() < 1)
return 0.0;
// 初始化,因为乘积需要考虑负数情况,所以要设置一个minN来保存最小值
double maxN = arr[0];
double minN = arr[0];
double res = arr[0];;
for(int i = 1; i < n; i++) {
// 保存上一步的最大值和最小值
double mx = maxN, mi = minN;
maxN = max(mx * arr[i], max(arr[i], mi * arr[i]));
minN = min(mi * arr[i], min(arr[i], mx * arr[i]));
res = max(res, maxN);
}
return res;
}
};