-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.cpp
More file actions
89 lines (75 loc) · 2.28 KB
/
Copy pathsolution.cpp
File metadata and controls
89 lines (75 loc) · 2.28 KB
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
class Solution
{
static const long long MOD = 1000000007LL;
// I use fast power to find modular inverse under MOD.
long long modPow(long long base, long long exp)
{
long long result = 1;
base %= MOD;
while (exp > 0)
{
if (exp & 1)
{
result = (result * base) % MOD;
}
base = (base * base) % MOD;
exp >>= 1;
}
return result;
}
public:
int findMaxProduct(vector<int> &arr)
{
int n = (int)arr.size();
// If there is only one number, I return it directly.
// This keeps the answer correct for cases like [-1].
if (n == 1)
{
return arr[0];
}
int zeroCount = 0;
int positiveCount = 0;
int negativeCount = 0;
// I store the smallest absolute value among negative numbers.
// If negatives are odd, this is the one I remove.
int minNegAbs = 11;
long long product = 1;
for (int x : arr)
{
if (x == 0)
{
zeroCount++;
continue; // Zero does not help the product unless everything is bad.
}
if (x > 0)
{
positiveCount++;
}
else
{
negativeCount++;
minNegAbs = min(minNegAbs, abs(x));
}
// I multiply absolute values so the product stays non-negative here.
product = (product * (long long)abs(x)) % MOD;
}
// If all elements are zero, the best product is zero.
if (zeroCount == n)
{
return 0;
}
// If there is exactly one negative and everything else is zero,
// zero is better than a negative product.
if (negativeCount == 1 && positiveCount == 0)
{
return 0;
}
// If the number of negatives is odd, I remove the smallest absolute negative.
if (negativeCount % 2 == 1)
{
long long inv = modPow(minNegAbs, MOD - 2);
product = (product * inv) % MOD;
}
return (int)product;
}
};