#2172
Maximum AND Sum of Array
HardArrayDynamic ProgrammingBit ManipulationBitmaskDynamic ProgrammingBitmaskingBacktracking
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n!) | O(n * 2^m) |
| Space | O(n) | O(2^m) |
💡
Intuition
Time O(n * 2^m)Space O(2^m)
The optimal solution uses dynamic programming with bitmasking to efficiently track the state of the slots and calculate the maximum AND sum. This approach significantly reduces the number of combinations we need to evaluate.
⚙️
Algorithm
3 steps- 1Step 1: Use a bitmask to represent the state of the slots, where each bit indicates whether a slot is filled and how many numbers it contains.
- 2Step 2: Use a recursive function with memoization to explore all possible placements of numbers into the slots while calculating the AND sum.
- 3Step 3: Return the maximum AND sum found across all valid placements.
solution.py14 lines
1def max_and_sum_optimal(nums, numSlots):
2 from functools import lru_cache
3 n = len(nums)
4 @lru_cache(None)
5 def dp(mask, count):
6 if count == n:
7 return 0
8 max_sum = 0
9 for i in range(numSlots):
10 if (mask >> i) & 3 < 2:
11 new_mask = mask | (1 << (i * 2)) | (1 << (i * 2 + 1))
12 max_sum = max(max_sum, (nums[count] & (i + 1)) + dp(new_mask, count + 1))
13 return max_sum
14 return dp(0, 0)ℹ
Complexity note: This complexity arises from the number of states represented by the bitmask (2^m) and the number of recursive calls (n) made for each state.
- 1Using bitmasking allows us to efficiently track the state of the slots.
- 2Dynamic programming helps avoid redundant calculations by storing previously computed results.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.