Maximum AND Sum of Array
Expert Answer & Key Takeaways
A complete guide to understanding and implementing Bit Manipulation.
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
Input: nums = [1,2,3,4,5,6], numSlots = 3
Output: 9
Approach 1
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.
⏱ $O(numSlots^N)$💾 $O(N)$
Approach 2
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.
⏱ $O(N \cdot 3^{numSlots})$💾 $O(N \cdot 3^{numSlots})$
Approach 3
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
⏱ O(N \cdot 3^S) - Where $N$ is `nums.length` and $S$ is `numSlots`.💾 O(3^S) - Memoization table.
Course4All Technical Board
Verified ExpertSenior Software Engineers & Algorithmic Experts
Our DSA content is authored and reviewed by engineers from top tech firms to ensure optimal time and space complexity analysis.
Pattern: 2026 Ready
Updated: Weekly
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.