-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.cpp
More file actions
35 lines (28 loc) · 842 Bytes
/
Copy pathsolution.cpp
File metadata and controls
35 lines (28 loc) · 842 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class Solution
{
public:
int maxProduct(vector<int> &arr)
{
int n = arr.size();
// max product ending at current index
int maxEnding = arr[0];
// min product ending at current index
int minEnding = arr[0];
// overall maximum product
int result = arr[0];
for (int i = 1; i < n; i++)
{
// If current element is negative, swap
if (arr[i] < 0)
{
swap(maxEnding, minEnding);
}
// Update max and min product ending here
maxEnding = max(arr[i], maxEnding * arr[i]);
minEnding = min(arr[i], minEnding * arr[i]);
// Update result
result = max(result, maxEnding);
}
return result;
}
};