Maximum AND Sum of Array
Master this topic with zero to advance depth.
Maximum AND Sum of Array
Place n integers into numSlots slots (max 2 per slot). The AND sum is the sum of (nums[i] & slotNumber). Return the maximum possible AND sum.
Examples
Level I: Brute Force (Recursion)
Intuition
Try all possible placements of the integers into the slots. Each slot can take up to 2 integers. This is an exhaustive search of the solution space.
Level II: Greedy / Simple DP
Intuition
Identify that the problem has overlapping subproblems. Even without a full ternary mask, we can use a simpler memoization based on the current counts array (converted to a string or tuple) to avoid redundant work.
Level III: Bitmask DP (Ternary / Base-3)
Intuition
Since each slot can hold up to 2 integers, we can represent the state of the slots using a base-3 integer. In this integer, the -th digit (in base 3) represents the number of elements in slot (0, 1, or 2).
Thought Process
- Use a recursive function
solve(index, mask)whereindexis the current number innumswe are placing. - The
maskis a base-3 representation of slot occupancies. - For each slot :
- Check if slot has items.
- If yes, place
nums[index]in slot , update mask, and take the results.
Pattern: Base-N Bitmasking
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.