Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.
- new solution update 2022.02.06
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19class Solution {
public:
int maxProduct(vector<int>& nums) {
int res = nums[0], cur = 1, negative = 1;
for(int i = 0; i < nums.size(); i++) {
if(nums[i]) {
cur *= nums[i];
res = max(res, cur);
if(negative < 0) res = max(res, cur / negative);
else if(negative > 0 and cur < 0) negative = cur;
} else {
negative = 1;
cur = 1;
res = max(res, 0);
}
}
return res;
}
};
1 | class Solution { |