Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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 ?
Start with bit position
i = 0andans = 0For each bit position, check all numbers
If a number has 0 at position
i, flip it and add2^ito the answerDecrement
kand stop ifk = 0Move to the next bit position
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) & 1checks if bit at position i is setReturns 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.
