Skip to content

Commit 09f6a53

Browse files
authored
Create count-good-meals.cpp
1 parent 3aef8c8 commit 09f6a53

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

C++/count-good-meals.cpp

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
// Time: O(n)
2+
// Space: O(1)
3+
4+
class Solution {
5+
public:
6+
int countPairs(vector<int>& deliciousness) {
7+
static const int MOD = 1e9 + 7;
8+
9+
static const auto& floor_log2_x = [](int x) {
10+
return 8 * sizeof(int) - __builtin_clz(x) - 1;
11+
};
12+
13+
int max_pow = floor_log2_x(*max_element(cbegin(deliciousness),
14+
cend(deliciousness))) + 1;
15+
unordered_map<int, int> cnt;
16+
int result = 0;
17+
for (const auto& d : deliciousness) {
18+
int p = 1;
19+
for (int i = 0; i <= max_pow; ++i) {
20+
result = (result + cnt[p - d]) % MOD;
21+
p <<= 1;
22+
}
23+
++cnt[d];
24+
}
25+
return result;
26+
}
27+
};

0 commit comments

Comments
 (0)