A good meal is a meal that contains exactly two different food items with a sum of deliciousness equal to a power of two.
You can pick any two different foods to make a good meal.
Given an array of integers deliciousness
where deliciousness[i]
is the deliciousness of the ith
item of food, return the number of different good meals you can make from this list modulo 109 + 7
.
Note that items with different indices are considered different even if they have the same deliciousness value.
Example 1:
Input: deliciousness = [1,3,5,7,9] Output: 4 Explanation: The good meals are (1,3), (1,7), (3,5) and, (7,9). Their respective sums are 4, 8, 8, and 16, all of which are powers of 2.
Example 2:
Input: deliciousness = [1,1,1,3,3,3,7] Output: 15 Explanation: The good meals are (1,1) with 3 ways, (1,3) with 9 ways, and (1,7) with 3 ways.
Constraints:
1 <= deliciousness.length <= 105
0 <= deliciousness[i] <= 220
Related Topics:
Array, Hash Table, Two Pointers
Similar Questions:
Use an unordered_map<int, int> m
to store the frequency of each number in array A
(i.e. m[a]
is the frequency of a
).
Since A[i]
is in range [0, 2^20]
, the sum of two numbers is in range [0, 2^21]
.
For each pair a, cnt
in m
, we try to find if b = sum - a
is in m
as well, where sum
is power of 2
.
To avoid repetitive computation, we skip a b
value if b < a
.
If a == b
, add cnt * (cnt - 1) / 2
to answer.
Otherwise, add cnt * m[b]
to answer.
// OJ: https://leetcode.com/problems/count-good-meals/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(N)
class Solution {
public:
int countPairs(vector<int>& A) {
long mod = 1e9 + 7, ans = 0;
unordered_map<int, int> m;
for (int n : A) m[n]++;
for (auto &[a, cnt] : m) {
for (int i = 0; i <= 21; ++i) {
long b = (1 << i) - a;
if (b < a || m.count(b) == 0) continue;
long c = m[b];
if (a == b) ans = (ans + (c * (c - 1) / 2) % mod) % mod;
else ans = (ans + cnt * c % mod) % mod;
}
}
return ans;
}
};