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 of Array INPUT nums array: 1 2 3 4 5 6 numSlots = 3 Slot 1 Slot 2 Slot 3 Constraint: Each slot holds at most 2 numbers AND operation example: 5 AND 3 = 101 AND 011 = 001 = 1 ALGORITHM STEPS 1 State Encoding Use base-3 mask for slots (0,1,2 items per slot) 2 DP Transition For each num, try all slots with capacity 3 Calculate AND Sum Add (num AND slot_idx) to current state 4 Find Maximum Track max sum across all valid placements DP State Space dp[mask] = max AND sum mask encodes slot usage States: 3^numSlots FINAL RESULT Optimal Assignment: Slot 1 1, 5 Slot 2 2, 6 Slot 3 3, 4 AND Sum Calculation: 1 AND 1 = 1 5 AND 1 = 1 2 AND 2 = 2 6 AND 2 = 2 3 AND 3 = 3 4 AND 3 = 0 Sum = 1+1+2+2+3+0 Output: 9 Maximum AND Sum = 9 Key Insight: Bitmask DP with base-3 encoding allows tracking slot occupancy (0, 1, or 2 items). Each state represents a unique assignment configuration. Time complexity: O(n * 3^numSlots * numSlots) where we iterate through all numbers and try placing each in available slots. TutorialsPoint - Maximum AND Sum of Array | Optimized Bitmask DP
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