MediumNo. 2680
Maximum OR — LeetCode 2680 Python Solution
- Pattern
- Prefix Sum
- Topics
- Greedy, Bit Manipulation, Array, Prefix Sum
- Reading time
- 2 min
- Source
- leetcode.com
The problem
You are given a 0-indexed integer array nums of length n and an integer k. In an operation, you can choose an element and multiply it by 2.
Example
- Input
- nums = [12,9], k = 1
- Output
- 30
- Explanation
- If we apply the operation to index 1, our new array nums will be equal to [12,18]. Thus, we return the bitwise or of 12 and 18, which is 30.
Python solution
class Solution:
def maximumOr(self, nums: List[int], k: int) -> int:
n = len(nums)
suf = [0] * (n + 1)
for i in range(n - 1, -1, -1):
suf[i] = suf[i + 1] | nums[i]
ans = pre = 0
for i, x in enumerate(nums):
ans = max(ans, pre | (x << k) | suf[i + 1])
pre |= x
return ansComplexity
- Time
- O(n)
- Space · auxiliary
- O(n)
Pattern: Prefix Sum
Precompute running totals once so any range query becomes a single subtraction. LeetCode 2680. Maximum OR is filed here because LeetCode tags it Prefix Sum, which is the vocabulary this hub collects.
The prefix sum guide has the Python template for the pattern and the 157 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0861 | Score After Flipping Matrix | Medium |
| 1558 | Minimum Numbers of Function Calls to Make Target Array | Medium |
| 1589 | Maximum Sum Obtained of Any Permutation | Medium |
| 1703 | Minimum Adjacent Swaps for K Consecutive Ones | Hard |
| 1838 | Frequency of the Most Frequent Element | Medium |
| 2132 | Stamping the Grid | Hard |
Frequently asked questions
- How hard is LeetCode 2680. Maximum OR?
LeetCode 2680. Maximum OR is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2680. Maximum OR?
The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 2680. Maximum OR?
The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 2680. Maximum OR cover?
LeetCode 2680. Maximum OR is tagged Greedy, Bit Manipulation, Array and Prefix Sum on LeetCode.