Maximum Bitwise AND by Increment

You have an array of integers nums and a budget of k increments. Each increment increases a chosen number by exactly 1.

Your task is to pick exactly m elements from the array and increment them optimally so that the Bitwise AND of those m elements is as large as possible. Return the maximum possible Bitwise AND.

Example 1:

Input: nums = [3, 1, 2], k = 8, m = 2

Output: 6

Explanation: Choose indices [0, 2] -> [3, 2]. Increment 3 to 6 (cost: 3 operations). Increment 2 to 6 (cost: 4 operations).

Hence Total cost = 7 <= 8. Subset is [6, 6]. 6 & 6 = 6.

Example 2:

Input: nums = [1, 2, 8, 4], k = 7, m = 3

Output: 4

Explanation: Choose indices [0, 1, 3] -> values [1, 2, 4]. Increment 1 to 4 (cost: 3). Increment 2 to 4 (cost: 2).

Keep 4 as 4 (cost: 0).

Hence Total cost = 5 <= 7. Subset is [4, 4, 4]. 4 & 4 & 4 = 4.

Now Your Turn!

Pick the correct output for the given input

Input: nums = [1, 1, 2], k = 0, m = 2

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 <= n == nums.length <= 5 * 104
  • 1 <= nums[i] <= 109
  • 1 <= k <= 109
  • 1 <= m <= n

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

0
class Solution {
public:
int maximumAND(vector<int>& nums, int k, int m) {
// Write your code here
return 0;
}
};
Test Case

Input:

K
M
Nums