Skip to content

2680. Maximum OR 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
 public:
  long long maximumOr(vector<int>& nums, int k) {
    const int n = nums.size();
    long ans = 0;
    // prefix[i] := nums[0] | nums[1] | ... | nums[i - 1]
    vector<long> prefix(n);
    // suffix[i] := nums[i + 1] | nums[i + 2] | ... nums[n - 1]
    vector<long> suffix(n);

    for (int i = 1; i < n; ++i)
      prefix[i] = prefix[i - 1] | nums[i - 1];

    for (int i = n - 2; i >= 0; --i)
      suffix[i] = suffix[i + 1] | nums[i + 1];

    // For each num, greedily shift it left by k bits.
    for (int i = 0; i < n; ++i)
      ans = max(ans, prefix[i] | static_cast<long>(nums[i]) << k | suffix[i]);

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
  public long maximumOr(int[] nums, int k) {
    final int n = nums.length;
    long ans = 0;
    // prefix[i] := nums[0] | nums[1] | ... | nums[i - 1]
    long[] prefix = new long[n];
    // suffix[i] := nums[i + 1] | nums[i + 2] | ... nums[n - 1]
    long[] suffix = new long[n];

    for (int i = 1; i < n; ++i)
      prefix[i] = prefix[i - 1] | nums[i - 1];

    for (int i = n - 2; i >= 0; --i)
      suffix[i] = suffix[i + 1] | nums[i + 1];

    // For each num, greedily shift it left by k bits. The bitwise or value is
    // prefix[i] | nums[i] << k | suffix[i]
    for (int i = 0; i < n; ++i)
      ans = Math.max(ans, prefix[i] | (long) nums[i] << k | suffix[i]);

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution:
  def maximumOr(self, nums: list[int], k: int) -> int:
    n = len(nums)
    # prefix[i] := nums[0] | nums[1] | ... | nums[i - 1]
    prefix = [0] * n
    # suffix[i] := nums[i + 1] | nums[i + 2] | ... nums[n - 1]
    suffix = [0] * n

    for i in range(1, n):
      prefix[i] = prefix[i - 1] | nums[i - 1]

    for i in range(n - 2, -1, -1):
      suffix[i] = suffix[i + 1] | nums[i + 1]

    # For each num, greedily shift it left by k bits.
    return max(p | num << k | s for num, p, s in zip(nums, prefix, suffix))