LeetCode 1711: Count Good Meals
Problem Description
Explanation:
To solve this problem, we can iterate through the deliciousness array and keep track of the counts of each deliciousness value in a hashmap. For each deliciousness value, we check if there exists another deliciousness value that forms a good meal with it (i.e., the sum is a power of two).
We iterate through all powers of two up to 2 * the maximum deliciousness value in the input array. For each power of two, we calculate the complement needed to form a good meal. We then check if the complement exists in the hashmap. If it does, we increment the count of good meals by the product of the counts of the current deliciousness value and the complement.
Finally, we return the count of good meals modulo 10^9 + 7.
Time complexity: O(n * log(max_d)), where n is the number of items in the deliciousness array and max_d is the maximum deliciousness value in the array. Space complexity: O(n), to store the counts of each deliciousness value in the hashmap.
:
Solutions
class Solution {
public int countPairs(int[] deliciousness) {
Map<Integer, Integer> countMap = new HashMap<>();
int MOD = 1000000007;
long ans = 0;
for (int d : deliciousness) {
for (int i = 0; i <= 21; i++) {
int target = (1 << i) - d;
if (countMap.containsKey(target)) {
ans += countMap.get(target);
ans %= MOD;
}
}
countMap.put(d, countMap.getOrDefault(d, 0) + 1);
}
return (int) ans;
}
}
Loading editor...