LeetCode 2680. Maximum OR Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
2680. Maximum OR

Description

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.

Return the maximum possible value of nums[0] | nums[1] | ... | nums[n - 1] that can be obtained after applying the operation on nums at most k times.

Note that a | b denotes the bitwise or between two integers a and b.

 

Example 1:

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.

Example 2:

Input: nums = [8,1,2], k = 2
Output: 35
Explanation: If we apply the operation twice on index 0, we yield a new array of [32,1,2]. Thus, we return 32|1|2 = 35.

 

Constraints:

  • 1 <= nums.length <= 105
  • 1 <= nums[i] <= 109
  • 1 <= k <= 15

Solutions

Solution 1: Greedy + Preprocessing

We notice that in order to maximize the answer, we should apply k times of bitwise OR to the same number.

First, we preprocess the suffix OR value array suf of the array nums, where suf[i] represents the bitwise OR value of nums[i], nums[i + 1], …, nums[n - 1].

Next, we traverse the array nums from left to right, and maintain the current prefix OR value pre. For the current position i, we perform k times of bitwise left shift on nums[i], i.e., nums[i] × 2k, and perform bitwise OR operation with pre to obtain the intermediate result. Then, we perform bitwise OR operation with suf[i + 1] to obtain the maximum OR value with nums[i] as the last number. By enumerating all possible positions i, we can obtain the final answer.

The time complexity is O(n), and the space complexity is O(n). Here, n is the length of the array nums.

PythonJavaC++GoTypeScriptRust
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 ans(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !