#2680
Maximum OR
MediumArrayGreedyBit ManipulationPrefix SumBit ManipulationGreedy Algorithms
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
Instead of trying all combinations, we can focus on maximizing the OR by applying all k operations to a single element. This is because multiplying one number maximally increases its contribution to the overall OR.
⚙️
Algorithm
3 steps- 1Step 1: Calculate the initial OR of the entire array.
- 2Step 2: For each element, calculate the OR after applying k multiplications to that element.
- 3Step 3: Keep track of the maximum OR obtained from all elements.
solution.py10 lines
1def maxOR(nums, k):
2 initial_or = 0
3 for num in nums:
4 initial_or |= num
5 max_or = initial_or
6 for num in nums:
7 modified_num = num * (2 ** k)
8 current_or = initial_or | modified_num
9 max_or = max(max_or, current_or)
10 return max_orℹ
Complexity note: This complexity is linear because we only traverse the array a couple of times, making it efficient for large inputs.
- 1Maximizing OR is best achieved by focusing operations on a single element.
- 2The bitwise OR operation accumulates bits, so larger numbers contribute more.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.