Given an array of integers P = [P1, P2, ...] and a function F(M) that returns the XOR of all integers present in set M. If M is empty, then F(M) = 0.
The task is to find the maximum possible value of the expression N XOR F(M) over all possible subsets M of P. Here, N is an integer given to us as an input.
Formally, find the value of max(N XOR F(M)), where M is a subset of P and N can be any integer that is less than or equal to 1000.
Example:
Sample Input:
N = 4
P = [1, 2, 3]
Numofintegers = 3
Sample Output :
7
Constraints :
Pi <= 1000
Number of integers <= 1000
N <= 1000
Need an optimized solution for this preferably in Python
I used this approach to solve this but the complexity is too bad - O(2 ^ N) with brute force
from itertools import combinations
def find_max_xor(N,P):
# find the maximum XOR value
comb = []
for i in range(len(P) + 1):
comb += [list(j) for j in combinations([1,2,3], i)]
arr = []
for i in comb:
if len(i):
res = 0
for l in range(len(i)):
res ^= i[l]
arr.append(N ^ res)
return max(arr)
n = 4
p = [1,2,3]
# numIntegers = 3
result = find_max_xor(n,p)
print("result : ", result)