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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code