Skip to content

2317. Maximum XOR After Operations

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
 public:
  int maximumXOR(vector<int>& nums) {
    // 1. nums[i] & (nums[i] ^ x) enables you to turn 1-bit to 0-bit from
    //    nums[i] since x is arbitrary.
    // 2. The i-th bit of the XOR of all the elements is 1 if the i-th bit is 1
    //    for an odd number of elements.
    // 3. Therefore, the question is equivalent to: if you can convert any digit
    //    from 1 to 0 for any number, what is the maximum for XOR(nums[i]).
    // 4. The maximum we can get is of course to make every digit of the answer
    //    to be 1 if possible
    // 5. Therefore, OR(nums[i]) is an approach.
    return reduce(nums.begin(), nums.end(), 0, bit_or());
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
  public int maximumXOR(int[] nums) {
    // 1. nums[i] & (nums[i] ^ x) enables you to turn 1-bit to 0-bit from
    //    nums[i] since x is arbitrary.
    // 2. The i-th bit of the XOR of all the elements is 1 if the i-th bit is 1
    //    for an odd number of elements.
    // 3. Therefore, the question is equivalent to: if you can convert any digit
    //    from 1 to 0 for any number, what is the maximum for XOR(nums[i]).
    // 4. The maximum we can get is of course to make every digit of the answer
    //    to be 1 if possible
    // 5. Therefore, OR(nums[i]) is an approach.
    return Arrays.stream(nums).reduce(0, (a, b) -> a | b);
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution:
  def maximumXOR(self, nums: list[int]) -> int:
    # 1. nums[i] & (nums[i] ^ x) enables you to turn 1-bit to 0-bit from
    #    nums[i] since x is arbitrary.
    # 2. The i-th bit of the XOR of all the elements is 1 if the i-th bit is 1
    #    for an odd number of elements.
    # 3. Therefore, the question is equivalent to: if you can convert any digit
    #    from 1 to 0 for any number, what is the maximum for XOR(nums[i]).
    # 4. The maximum we can get is of course to make every digit of the answer
    #    to be 1 if possible
    # 5. Therefore, OR(nums[i]) is an approach.
    return functools.reduce(operator.ior, nums)