All Downloads are FREE. Search and download functionalities are using the official Maven repository.

g1701_1800.s1711_count_good_meals.Solution Maven / Gradle / Ivy

There is a newer version: 1.41
Show newest version
package g1701_1800.s1711_count_good_meals;

// #Medium #Array #Hash_Table #2022_04_24_Time_75_ms_(93.77%)_Space_74.5_MB_(63.96%)

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * 1711 - Count Good Meals\.
 *
 * Medium
 *
 * 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
**/
public class Solution {
    public int countPairs(int[] d) {
        HashMap map = new HashMap<>();
        for (int k : d) {
            map.put(k, map.getOrDefault(k, 0) + 1);
        }
        long result = 0;
        for (Iterator> it = map.entrySet().iterator(); it.hasNext(); ) {
            Map.Entry elem = it.next();
            int key = elem.getKey();
            long value = elem.getValue();
            for (int j = 21; j >= 0; j--) {
                int find = (1 << j) - key;
                if (find < 0) {
                    break;
                }
                if (map.containsKey(find)) {
                    if (find == key) {
                        result += (((value - 1) * value) / 2);
                    } else {
                        result += (value * map.get(find));
                    }
                }
            }
            it.remove();
        }
        int mod = 1_000_000_007;
        return (int) (result % mod);
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy