[LeetCode] Count Good Meals

1711. Count Good Meals

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 i​​​​​​th​​​​​​​​ 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.

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
class Solution {
public:
int countPairs(vector<int>& deliciousness) {
map<int, long long> meals;
set<int> powerOfTwo;
for(int i = 0; i <= 21; i++) {
powerOfTwo.insert(1<<i);
}
long long res = 0;

for(int num : deliciousness) {
meals[num]++;
}

for(auto meal : meals) {
for(auto num = powerOfTwo.lower_bound(meal.first<<1); num != powerOfTwo.end(); num++) {
auto it = meals.lower_bound(*num - meal.first);
if(it == meals.end())
break;
if(it->first + meal.first == *num) {
if(it->first == meal.first)
res += it->second * (meal.second - 1) / 2;
else
res += it->second * meal.second;
}
}
}

return res % 1000000007;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/01/20/PS/LeetCode/count-good-meals/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.