Program to find minimum possible sum by changing 0s to 1s k times from a list of numbers in Python?


Suppose we have a list of numbers called nums and another value k. We have to following operation k times: Select any number on the list. In the binary representation of that number, select a bit that is 0 and make it 1. Finally, we have to return the minimum possible sum of all the numbers after performing k operations. If the answer is too high, return result mode 10^9+7.

So, if the input is like nums = [4, 7, 3] k = 2, then the output will be 17, as the binary representation of 4 is 100, 3 is 011, and 7 is 111. Since we need to set 2 bits, we can set the bits of 4 to make it 111 (7). Then the total sum is then 7 + 7 + 3 = 17.

To solve this, we will follow these steps:

  • ans := 0, i := 0

  • while k is non-zero, do

    • for each n in nums, do

      • if (n / 2^i) is even, then

        • ans := ans + 2^i

        • k := k - 1

        • if k is same as 0, then

          • come out from the loop

    • i := i + 1

  • return (ans + sum of all elements of nums) mod m

Let us see the following implementation to get better understanding:

Example

 Live Demo

class Solution:
   def solve(self, nums, k):
      m = (10 ** 9 + 7)
      ans = 0
      i = 0
      while k:
         for n in nums:
            if (n >> i) & 1 == 0:
               ans += 1 << i
               k -= 1
               if k == 0:
                  break
                  i += 1
      return (ans + sum(nums)) % m

ob = Solution()
nums = [4, 7, 3]
k = 2
print(ob.solve(nums, k))

Input

[4, 7, 3], 2

Output

17

Updated on: 10-Nov-2020

70 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements