Maximum OR — LeetCode 2680 Python Solution
MediumGreedyBit ManipulationArrayPrefix Sum
- Problem
- #2680
- Pattern
- 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
Python
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
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
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
LeetCode 861Score After Flipping MatrixMediumLeetCode 1558Minimum Numbers of Function Calls to Make Target ArrayMediumLeetCode 1589Maximum Sum Obtained of Any PermutationMediumLeetCode 1703Minimum Adjacent Swaps for K Consecutive OnesHardLeetCode 1838Frequency of the Most Frequent ElementMediumLeetCode 2132Stamping the GridHard
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.