Maximum Product of Two Integers With No Common Bits Problem
Description
LeetCode Problem 3670.
You are given an integer array nums.
Your task is to find two distinct indices i and j such that the product nums[i] * nums[j] is maximized, and the binary representations of nums[i] and nums[j] do not share any common set bits.
Return the maximum possible product of such a pair. If no such pair exists, return 0.
Example 1:
Input: nums = [1,2,3,4,5,6,7]
Output: 12
Explanation:
The best pair is 3 (011) and 4 (100). They share no set bits and 3 * 4 = 12.
Example 2:
Input: nums = [5,6,4]
Output: 0
Explanation:
Every pair of numbers has at least one common set bit. Hence, the answer is 0.
Example 3:
Input: nums = [64,8,32]
Output: 2048
Explanation:
No pair of numbers share a common bit, so the answer is the product of the two maximum elements, 64 and 32 (64 * 32 = 2048).
Constraints:
2 <= nums.length <= 10^51 <= nums[i] <= 10^6
Solution
Approach: Subset Maximum (SOS DP)
Two numbers share no set bit exactly when one is a subset of the complement of the other. Let bits be the bit length of the largest number and full = 2^bits - 1.
Define best[m] as the largest number in nums whose set bits all lie inside mask m (0 if there is none). Start with best[x] = x for every x in nums, then for each bit b and each mask m containing b, set best[m] = max(best[m], best[m without b]). After this, best[m] covers all submasks of m.
For every x, the best partner is best[full ^ x]. It can never be x itself, because x >= 1 shares bits with itself, so the two indices are distinct. The answer is the largest x * best[full ^ x] (0 if no pair exists). Products need 64 bits.
Complexity: time O(n + M log M), space O(M), where M is the largest value (about 2^20).
class Solution:
def maxProduct(self, nums: List[int]) -> int:
bits = max(nums).bit_length()
size = 1 << bits
full = size - 1
# best[m]: the largest number in nums whose bits are all inside mask m (0 if none)
best = [0] * size
for x in nums:
best[x] = x
for b in range(bits):
step = 1 << b
if step * step * 2 <= size:
# few offsets: update each residue class with one strided slice
for r in range(step):
best[step + r::2 * step] = map(max, best[step + r::2 * step], best[r::2 * step])
else:
for s in range(0, size, step * 2):
best[s + step:s + 2 * step] = map(max, best[s + step:s + 2 * step], best[s:s + step])
ans = 0
for x in nums:
y = best[full ^ x]
if x * y > ans:
ans = x * y
return ans