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

Given a list of numbers and a value k, we need to perform k operations where each operation flips a 0 bit to 1 in any number's binary representation. The goal is to minimize the final sum of all numbers.

For example, if nums = [4, 7, 3] and k = 2, the binary representations are:

  • 4 ? 100 (binary)

  • 7 ? 111 (binary)

  • 3 ? 011 (binary)

We can flip two 0 bits in 4 (positions 0 and 1) to make it 111 (7). Final sum: 7 + 7 + 3 = 17.

Algorithm

The strategy is to process bit positions from least significant (rightmost) to most significant, flipping 0 bits to 1s greedily ?

  1. Start with bit position i = 0 and ans = 0

  2. For each bit position, check all numbers

  3. If a number has 0 at position i, flip it and add 2^i to the answer

  4. Decrement k and stop if k = 0

  5. Move to the next bit position

  6. Return the sum of original numbers plus the added value

Example

class Solution:
    def solve(self, nums, k):
        m = (10 ** 9 + 7)
        ans = 0
        i = 0
        
        while k:
            for n in nums:
                # Check if bit at position i is 0
                if (n >> i) & 1 == 0:
                    ans += 1 << i  # Add 2^i
                    k -= 1
                    if k == 0:
                        break
            i += 1
        
        return (ans + sum(nums)) % m

# Test the solution
ob = Solution()
nums = [4, 7, 3]
k = 2
result = ob.solve(nums, k)
print(f"Input: nums = {nums}, k = {k}")
print(f"Output: {result}")
Input: nums = [4, 7, 3], k = 2
Output: 17

How It Works

Let's trace through the example step by step ?

nums = [4, 7, 3]  # Binary: [100, 111, 011]
k = 2

# Bit position 0 (rightmost):
# 4 (100): bit 0 is 0 ? flip it, add 2^0 = 1, k = 1
# 7 (111): bit 0 is 1 ? skip
# 3 (011): bit 0 is 1 ? skip

# Bit position 1:
# 4 (100): bit 1 is 0 ? flip it, add 2^1 = 2, k = 0

# Total added: 1 + 2 = 3
# Original sum: 4 + 7 + 3 = 14
# Final result: 14 + 3 = 17

print("Binary representations:")
for num in [4, 7, 3]:
    print(f"{num} ? {bin(num)[2:].zfill(3)}")
Binary representations:
4 ? 100
7 ? 111
3 ? 011

Key Points

  • The algorithm processes bits from least to most significant positions

  • Greedy approach: flip the smallest possible bits first

  • Uses bit manipulation: (n >> i) & 1 checks if bit at position i is set

  • Returns result modulo 10^9 + 7 to handle large numbers

Conclusion

This greedy algorithm minimizes the sum by flipping the least significant 0 bits first. The time complexity is O(n × log(max_value)) where n is the length of nums.

Updated on: 2026-03-25T12:07:34+05:30

182 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements