#3806

Maximum Bitwise AND After Increment Operations

Hard
ArrayGreedyBit ManipulationSortingGreedyBit Manipulation
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

Use a greedy approach to maximize the AND bit by bit, starting from the highest bit. This ensures we use increments efficiently.

⚙️

Algorithm

3 steps
  1. 1Step 1: Iterate from the highest bit to the lowest (31 to 0).
  2. 2Step 2: For each bit, check if we can set it in the result by counting how many numbers can be incremented to have that bit set.
  3. 3Step 3: If we can set the bit with available increments, update the result.
solution.py9 lines
1def max_bitwise_and(nums, k, m):
2    res = 0
3    for bit in range(31, -1, -1):
4        count = sum((num | res) >> bit & 1 for num in nums)
5        needed = m - count
6        if needed <= k:
7            res |= (1 << bit)
8            k -= needed
9    return res

Complexity note: The complexity is linear since we iterate through the bits (constant) and check each number once.

  • 1Maximizing bits from highest to lowest is efficient.
  • 2Increment operations should be used wisely to achieve the desired bitwise AND.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.