-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path2031.cpp
More file actions
43 lines (40 loc) · 1.08 KB
/
2031.cpp
File metadata and controls
43 lines (40 loc) · 1.08 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
class Counter {
private:
vector<int> counts;
public:
Counter() {
// allow -1e5 ~ 1e5
counts.resize(1e5 * 2 + 1, 0);
}
void add(int value) {
counts[value + 1e5]++;
}
int getCount(int index) {
return counts[index + 1e5];
}
};
class Solution {
public:
int subarraysWithMoreZerosThanOnes(vector<int>& nums) {
int n = nums.size();
vector<int> prefixSum(n + 1, 0);
for (int i = 0; i < n; ++i) {
prefixSum[i + 1] = prefixSum[i] + (nums[i] == 1 ? 1 : -1);
}
long long res = 0;
const long long mod = 1e9 + 7;
Counter* counter = new Counter();
long long preValue = 0;
long long preCount = 0;
for (auto& num : prefixSum) {
if (num == preValue + 1) preCount += counter->getCount(preValue);
else preCount -= counter->getCount(preValue - 1);
counter->add(num);
preValue = num;
preCount %= mod;
res += preCount;
res %= mod;
}
return res;
}
};