Count Good Meals in Python

PythonServer Side ProgrammingProgramming

A good meal 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.

Let us suppose we have given an array of integers arr where arr[i] is the deliciousness of the ith item of food, return the number of different good meals you can make from this list.

For example,

Input-1

arr[ ] = {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.

Input-2

arr[ ]= {1,1,1,3,3,3,7}

Output

15

Explanation − The good meals are (1,1) in 3 ways, (1,3) in 9 ways, and (1,7) in 3 ways.

The approach used to solve this problem

  • Take input as an array of positive integers.

  • A function count pairs take all the array elements as a list of integers.

  • Sort the input array element in increasing order.

  • For every element of the array, find the maximum sum such that every element is in the power of ‘2’.

Example

class Solution:
   def countpairs(self, arr: List[int]) -> int:
      """
         elem1 + elem2 == 1 << i
         elem1 = 2 << i - elem2
      """
      result = 0
      seen = defaultdict(int)
      arr.sort()
      for d in arr:
         n = 1
         while n <= d + d:
            ans = (ans + seen[n-d]) % (10 ** 9 + 7)
            n = n << 1
         seen[d] += 1
      return ans
sol1= Solution()
print(sol1.countpairs([1,1,1,3,3,3,7]))

Output

4
raja
Published on 05-Feb-2021 07:13:23
Advertisements