LeetCode #3806 — HARD

Maximum Bitwise AND After Increment Operations

Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.

Solve on LeetCode
The Problem

Problem Statement

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 * 104
  • 1 <= nums[i] <= 109
  • 1 <= k <= 109
  • 1 <= m <= n
Patterns Used

Roadmap

  1. Brute Force Baseline
  2. Core Insight
  3. Algorithm Walkthrough
  4. Edge Cases
  5. Full Annotated Code
  6. Interactive Study Demo
  7. Complexity Analysis
Step 01

Brute Force Baseline

Problem summary: 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.

Baseline thinking

Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.

Pattern signal: Array · Greedy · Bit Manipulation

Example 1

[3,1,2]
8
2

Example 2

[1,2,8,4]
7
3

Example 3

[1,1]
3
2
Step 02

Core Insight

What unlocks the optimal approach

  • Use a greedy bitwise approach.
  • Iterate bits from highest to lowest and try setting the current bit in a candidate <code>res</code>.
  • To test a candidate, for each <code>num</code> compute the minimal increments needed so that <code>(num | candidate) == candidate</code>; take the smallest <code>m</code> costs and check if their sum <= <code>k</code>.
  • If feasible, keep the bit in <code>res</code> and continue with accumulated bits.
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03

Algorithm Walkthrough

Iteration Checklist

  1. Define state (indices, window, stack, map, DP cell, or recursion frame).
  2. Apply one transition step and update the invariant.
  3. Record answer candidate when condition is met.
  4. Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04

Edge Cases

Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Largest constraint values
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05

Full Annotated Code

Source-backed implementations are provided below for direct study and interview prep.

// Accepted solution for LeetCode #3806: Maximum Bitwise AND After Increment Operations
class Solution {
    public int maximumAND(int[] nums, int k, int m) {
        int max = 0;
        for (int x : nums) {
            max = Math.max(max, x);
        }
        max += k;

        int mx = 32 - Integer.numberOfLeadingZeros(max);
        int n = nums.length;

        int ans = 0;
        int[] cost = new int[n];

        for (int bit = mx - 1; bit >= 0; bit--) {
            int target = ans | (1 << bit);
            for (int i = 0; i < n; i++) {
                int x = nums[i];
                int diff = target & ~x;
                int j = diff == 0 ? 0 : 32 - Integer.numberOfLeadingZeros(diff);
                int mask = (1 << j) - 1;
                cost[i] = (target & mask) - (x & mask);
            }
            Arrays.sort(cost);
            long sum = 0;
            for (int i = 0; i < m; i++) {
                sum += cost[i];
            }
            if (sum <= k) {
                ans = target;
            }
        }

        return ans;
    }
}
Step 06

Interactive Study Demo

Use this to step through a reusable interview workflow for this problem.

Press Step or Run All to begin.
Step 07

Complexity Analysis

Time
O(n × log n × log M)
Space
O(n)

Approach Breakdown

EXHAUSTIVE
O(2ⁿ) time
O(n) space

Try every possible combination of choices. With n items each having two states (include/exclude), the search space is 2ⁿ. Evaluating each combination takes O(n), giving O(n × 2ⁿ). The recursion stack or subset storage uses O(n) space.

GREEDY
O(n log n) time
O(1) space

Greedy algorithms typically sort the input (O(n log n)) then make a single pass (O(n)). The sort dominates. If the input is already sorted or the greedy choice can be computed without sorting, time drops to O(n). Proving greedy correctness (exchange argument) is harder than the implementation.

Shortcut: Sort + single pass → O(n log n). If no sort needed → O(n). The hard part is proving it works.
Coach Notes

Common Mistakes

Review these before coding to avoid predictable interview regressions.

Off-by-one on range boundaries

Wrong move: Loop endpoints miss first/last candidate.

Usually fails on: Fails on minimal arrays and exact-boundary answers.

Fix: Re-derive loops from inclusive/exclusive ranges before coding.

Using greedy without proof

Wrong move: Locally optimal choices may fail globally.

Usually fails on: Counterexamples appear on crafted input orderings.

Fix: Verify with exchange argument or monotonic objective before committing.