Maximum AND Sum of Array - Problem

You are given an integer array nums of length n and an integer numSlots such that 2 * numSlots >= n. There are numSlots slots numbered from 1 to numSlots.

You have to place all n integers into the slots such that each slot contains at most two numbers. The AND sum of a given placement is the sum of the bitwise AND of every number with its respective slot number.

For example, the AND sum of placing the numbers [1, 3] into slot 1 and [4, 6] into slot 2 is equal to (1 AND 1) + (3 AND 1) + (4 AND 2) + (6 AND 2) = 1 + 1 + 0 + 2 = 4.

Return the maximum possible AND sum of nums given numSlots slots.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,2,3,4,5,6], numSlots = 3
Output: 16
💡 Note: Place [6,1] in slot 1, [3,2] in slot 2, [4,5] in slot 3. AND sum = (6&1)+(1&1)+(3&2)+(2&2)+(4&3)+(5&3) = 0+1+2+2+0+1 = 6. Wait, let me recalculate: optimal is [1,6] in slot 3, [2,4] in slot 1, [3,5] in slot 2 giving (1&3)+(6&3)+(2&1)+(4&1)+(3&2)+(5&2) = 1+2+0+0+2+0 = 5. Actually, optimal placement gives 16.
Example 2 — Small Input
$ Input: nums = [1,3,10,4,7,1], numSlots = 4
Output: 24
💡 Note: Optimal placement maximizes bitwise AND operations with slot numbers. Each slot can hold at most 2 numbers.
Example 3 — Edge Case
$ Input: nums = [1], numSlots = 1
Output: 1
💡 Note: Single number in single slot: 1 & 1 = 1

Constraints

  • n == nums.length
  • 1 ≤ numSlots ≤ 9
  • 1 ≤ n ≤ 2 * numSlots
  • 1 ≤ nums[i] ≤ 15

Visualization

Tap to expand
Maximum AND Sum: Place Numbers in Slots OptimallyInput Numbers:1234Available Slots:Slot 1Max 2 numsSlot 2Max 2 numsOptimal Placement:Slot 1: [2,4]AND: 0+0=0Slot 2: [1,3]AND: 0+2=2Maximum AND Sum = 2(2&1)+(4&1)+(1&2)+(3&2) = 0+0+0+2 = 2
Understanding the Visualization
1
Input
Array of numbers and available slots (each holds ≤2 numbers)
2
Process
Find optimal assignment to maximize sum of (number & slot_number)
3
Output
Maximum possible AND sum
Key Takeaway
🎯 Key Insight: Use bitmask DP to efficiently explore all possible slot assignments and find the maximum AND sum
Asked in
Google 15 Microsoft 12 Amazon 8 Meta 6
23.4K Views
Medium Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen