#3670
Maximum Product of Two Integers With No Common Bits
MediumArrayDynamic ProgrammingBit ManipulationBit ManipulationDynamic Programming
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n + B²) |
| Space | O(1) | O(B) |
💡
Intuition
Time O(n + B²)Space O(B)
Use bit masks to categorize numbers and find the maximum product without common bits efficiently.
⚙️
Algorithm
3 steps- 1Step 1: Create a list to store the maximum number for each bitmask (up to 2^20 for 1 ≤ nums[i] ≤ 10^6).
- 2Step 2: For each number, update the corresponding bitmask with the maximum value found.
- 3Step 3: Iterate through all pairs of masks, checking for no common bits and calculating the product.
solution.py10 lines
1def maxProduct(nums):
2 max_mask = [0] * (1 << 20)
3 for num in nums:
4 max_mask[num] = max(max_mask[num], num)
5 max_product = 0
6 for i in range(len(max_mask)):
7 for j in range(i + 1, len(max_mask)):
8 if (i & j) == 0:
9 max_product = max(max_product, max_mask[i] * max_mask[j])
10 return max_productℹ
Complexity note: We process each number once and check pairs of masks, where B is the bit-width (up to 20).
- 1Bit manipulation helps efficiently check for common bits.
- 2Using masks allows us to categorize numbers and maximize products.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.