Skip to content

Commit a6ffa9a

Browse files
committed
Add C++ solution for leetcode 152.
1 parent 1b230fe commit a6ffa9a

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
#include<vector>
2+
#include<algorithm>
3+
#include<iostream>
4+
using namespace std;
5+
6+
class Solution {
7+
public:
8+
int maxProduct(vector<int>& nums) {
9+
int res = nums[0]; /* 1 <= nums.length <= 2 * 10^4, -10 <= nums[i] <= 10 */
10+
int f = nums[0]; // f: 记录最大值f[i], g: 记录最小值g[i]
11+
int g = nums[0];
12+
const int N = nums.size();
13+
for (int i = 1; i < N; i++)
14+
{
15+
int a_i = nums[i];
16+
int fa = f*a_i;
17+
int ga = g*a_i;
18+
f = max(a_i, max(fa, ga));
19+
g = min(a_i, min(fa, ga));
20+
res = max(res, f); // 更新最终的最大值
21+
}
22+
return res;
23+
}
24+
};
25+
26+
// Test
27+
int main()
28+
{
29+
Solution sol;
30+
vector<int> nums = {2, 3, -2, 4};
31+
auto res = sol.maxProduct(nums);
32+
cout << res << endl;
33+
34+
return 0;
35+
}

0 commit comments

Comments
 (0)