Maximum OR - Problem
You're given an array of integers and a limited number of doubling operations. Your goal is to strategically apply these operations to maximize the bitwise OR of all elements in the array.
In each operation, you can choose any element and multiply it by 2 (which is equivalent to left-shifting its bits). You have at most k operations to work with.
Example: Given nums = [12, 9] and k = 1, you could double 12 to get 24, resulting in 24 | 9 = 25, or double 9 to get 18, resulting in 12 | 18 = 30. The optimal choice gives you 30.
The key insight is that bitwise OR combines all the set bits from different numbers, so you want to maximize the highest bits possible.
Input & Output
example_1.py โ Basic Case
$
Input:
nums = [12, 9], k = 1
โบ
Output:
30
๐ก Note:
We can apply the operation to nums[1] to make nums = [12, 18]. The maximum OR is 12 | 18 = 30.
example_2.py โ Multiple Operations
$
Input:
nums = [8, 1, 2], k = 2
โบ
Output:
35
๐ก Note:
We can apply the operations twice to nums[0] to make nums = [32, 1, 2]. The maximum OR is 32 | 1 | 2 = 35.
example_3.py โ Single Element
$
Input:
nums = [7], k = 3
โบ
Output:
56
๐ก Note:
With only one element, we apply all operations to it: 7 * 2^3 = 7 * 8 = 56.
Constraints
- 1 โค nums.length โค 105
- 1 โค nums[i] โค 109
- 1 โค k โค 15
- All array elements are positive integers
Visualization
Tap to expand
Understanding the Visualization
1
Analyze Impact
For each tower, calculate what the skyline would look like if you used all doubling stones on it
2
Use Shortcuts
Use prefix and suffix skylines to avoid recalculating the entire view each time
3
Find Optimal
The tower that produces the highest combined skyline wins
Key Takeaway
๐ฏ Key Insight: Concentrating all k operations on a single element maximizes the OR result because it creates the highest possible bit positions, and OR operations preserve all existing bits while adding the new high-order bits.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code