Maximum value of XOR among all triplets of an array in Python

In this article, we will learn how to find the maximum value of XOR among all the triplets of an array in Python. XOR is a logical operation the yield true when both the input of operator are different. For example, the XOR of A and B is A^B.

Example

Input: arr[] = {1, 2, 3, 4, 5}
Output: The maximum XOR value triplets in the given array is 7

Maximum Value of XOR in Python

1. Firstly, create a set s to avoid repetitions.

2. Declare variable res to store the final result.

3. Iterate the array from range (0,n) as outer loop and Iterate the array again from range(i,n) as an inner loop.

  • calculate the xor value and add it to set s
    s.add(arr[i]^arr[j])

4. Traverse the set s and iterate the array from range (0, n) as an inner loop.

  • Calculate the XOR value and find the maximum value using the max() function.
    res = max(res, i^arr[j])

5. Finally return res.

def maxXorTriplets(arr, n):
    s = set()
    for i in range(n):
        for j in range(i, n):
            s.add(arr[i]^arr[j])

    res = 0
    for i in s:
        for j in range(n):
            res = max(res, i^arr[j])
    return res

arr = [1, 2, 3, 4, 5, 8, 10, 11]
n = len(arr)
print("The given array: ", str(arr))
print("The maximum XOR value triplets in the given array is ",maxXorTriplets(arr, n))

Output

The given array: [1, 2, 3, 4, 5, 8, 10, 11]
The maximum XOR value triplets in the given array is 15

Also, read

Leave a Reply

Your email address will not be published.