LeetCode 1711: Count Good Meals Solution
Master LeetCode problem 1711 (Count Good Meals), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1711. Count Good Meals
Problem Explanation
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.
:
Solution Code
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;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1711 (Count Good Meals)?
This page provides optimized solutions for LeetCode problem 1711 (Count Good Meals) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1711 (Count Good Meals)?
The time complexity for LeetCode 1711 (Count Good Meals) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1711 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1711 in Java, C++, or Python.