Maximum AND Sum of Array — LeetCode 2172 Python Solution

HardBit ManipulationArrayDynamic ProgrammingBitmask
Problem
#2172
Reading time
3 min

The 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.

Example

Input
nums = [1,2,3,4,5,6], numSlots = 3
Output
9
Explanation
One possible placement is [1, 4] into slot 1, [2, 6] into slot 2, and [3, 5] into slot 3.

Python solution

Python
class Solution:
    def maximumANDSum(self, nums: List[int], numSlots: int) -> int:
        n = len(nums)
        m = numSlots << 1
        f = [0] * (1 << m)
        for i in range(1 << m):
            cnt = i.bit_count()
            if cnt > n:
                continue
            for j in range(m):
                if i >> j & 1:
                    f[i] = max(f[i], f[i ^ (1 << j)] + (nums[cnt - 1] & (j // 2 + 1)))
        return max(f)

Complexity

MeasureComplexity
TimeO(n·m) (typical)
SpaceO(n·m) or optimized auxiliary

Pattern: Bit Manipulation

Use XOR, masks and the low-bit trick to replace whole data structures with an integer. LeetCode 2172. Maximum AND Sum of Array is filed here because LeetCode tags it Bit Manipulation and Bitmask, which is the vocabulary this hub collects.

The bit manipulation guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2172. Maximum AND Sum of Array?
LeetCode 2172. Maximum AND Sum of Array is rated Hard on LeetCode.
What topics does LeetCode 2172. Maximum AND Sum of Array cover?
LeetCode 2172. Maximum AND Sum of Array is tagged Bit Manipulation, Array, Dynamic Programming and Bitmask on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview