490. Maximum Bitwise AND of Chosen Capacities After Increases
Asked in
Maximum Bitwise AND of Chosen Capacities After Increases

You are given a list of integers capacities and two integers deploymentSize and budget.

You may increase any capacity by any non-negative integer amount. The total of all increases across all capacities must not exceed budget.

After the increases, choose exactly deploymentSize capacities at distinct indices. Return the maximum possible bitwise AND of the chosen capacities.

Method Signature

int maxChosenAnd(List<Integer> capacities, int deploymentSize, int budget)
  • capacities: the starting capacity at each index
  • deploymentSize: the number of capacities to choose
  • budget: the largest allowed total of all increases
  • Returns the maximum possible bitwise AND of the chosen capacities

Constraints

  • 1 ≤ capacities.size() ≤ 50,000
  • 1 ≤ capacities[i] ≤ 1,000,000,000
  • 1 ≤ deploymentSize ≤ capacities.size()
  • 1 ≤ budget ≤ 1,000,000,000

Examples

Example 1

Input: maxChosenAnd(capacities = [5, 9, 12], deploymentSize = 2, budget = 4)

Output: 12

Explanation: Choose 9 and 12. Increase 9 by 3 so it becomes 12. The total increase is 3, which does not exceed 4. The AND is 12 AND 12 = 12. No choice reaches a larger AND within the budget.

Example 2

Input: maxChosenAnd(capacities = [6, 10, 3, 11], deploymentSize = 3, budget = 6)

Output: 11

Explanation: Choose 6, 10 and 11. Increase 6 by 5 and 10 by 1 so all three become 11. The total increase is 6, which does not exceed 6. The AND is 11 AND 11 AND 11 = 11.

Example 3

Input: maxChosenAnd(capacities = [6, 3], deploymentSize = 1, budget = 5)

Output: 11

Explanation: Only one capacity is chosen, so the AND is that capacity itself. Choose 6 and add the full budget of 5 to get 11.

Example 4

Input: maxChosenAnd(capacities = [7, 7, 7], deploymentSize = 3, budget = 2)

Output: 7

Explanation: All three capacities must be chosen. Keeping them unchanged gives 7 AND 7 AND 7 = 7. Getting a larger AND would need all three to reach at least 8, which costs at least 3 and exceeds the budget of 2.



Please use Laptop/Desktop or any other large screen to add/edit code.