Maximum Bitwise AND After Increment Operations Problem
Description
LeetCode Problem 3806.
You are given an integer array nums and two integers k and m.
You may perform at most k operations. In one operation, you may choose any index i and increase nums[i] by 1.
Return an integer denoting the maximum possible bitwise AND of any subset of size m after performing up to k operations optimally.
Example 1:
Input: nums = [3,1,2], k = 8, m = 2
Output: 6
Explanation:
- We need a subset of size m = 2. Choose indices [0, 2].
- Increase nums[0] = 3 to 6 using 3 operations, and increase nums[2] = 2 to 6 using 4 operations.
- The total number of operations used is 7, which is not greater than k = 8.
- The two chosen values become [6, 6], and their bitwise AND is 6, which is the maximum possible.
Example 2:
Input: nums = [1,2,8,4], k = 7, m = 3
Output: 4
Explanation:
- We need a subset of size m = 3. Choose indices [0, 1, 3].
- Increase nums[0] = 1 to 4 using 3 operations, increase nums[1] = 2 to 4 using 2 operations, and keep nums[3] = 4.
- The total number of operations used is 5, which is not greater than k = 7.
- The three chosen values become [4, 4, 4], and their bitwise AND is 4, which is the maximum possible.
Example 3:
Input: nums = [1,1], k = 3, m = 2
Output: 2
Explanation:
- We need a subset of size m = 2. Choose indices [0, 1].
- Increase both values from 1 to 2 using 1 operation each.
- The total number of operations used is 2, which is not greater than k = 3.
- The two chosen values become [2, 2], and their bitwise AND is 2, which is the maximum possible.
Constraints:
1 <= n == nums.length <= 5 * 10^41 <= nums[i] <= 10^91 <= k <= 10^91 <= m <= n
Solution
Approach: Greedy Bit by Bit
Decide the answer from the highest bit down. For each bit, try adding it to the current answer to get a target, and compute the cheapest way to raise each number so that it contains all bits of target.
For one number x, find the highest bit where target has a 1 and x has a 0, at position j - 1. Then the low j bits of x have to be raised to the low j bits of target, which costs (target & (2^j - 1)) - (x & (2^j - 1)). If there is no such bit, the cost is 0.
Sort the costs and add up the m smallest. If the total is at most k, keep the bit in the answer.
Complexity: Time O(n log n log M), space O(n), where n is the length of nums and M the largest possible value (max(nums) + k).
class Solution:
def maximumAND(self, nums: List[int], k: int, m: int) -> int:
mx = (max(nums) + k).bit_length()
ans = 0
cost = [0] * len(nums)
for bit in range(mx - 1, -1, -1):
target = ans | (1 << bit)
for i, x in enumerate(nums):
j = (target & ~x).bit_length()
mask = (1 << j) - 1
cost[i] = (target & mask) - (x & mask)
cost.sort()
if sum(cost[:m]) <= k:
ans = target
return ans