I am trying to solve this question where we have to find the maximum length of the subsequence such that XOR of each consecutive element is equal to k. e.g : Array = [3,2,4,3,5] and k=1. Answer would be 3. subsequence = [3,2,3]
So far I have tried these approaches :
- Naive two-loop solution where we will use two loops and find the subsequence with XOR equals to k.This approach is giving me timeout as the number of elements in the array can be up to 10^5.Psuedo Code :
int finalAns=0;
loop (i=0...n):
int xortillnow = array[i], count=1; // since we have already selected one element
loop(j=i+1..n):
if((xortillnow ^ array[i])==k):
count++;
xortillnow = xortillnow ^ array[i];
finalAns = max(count,finalAns);
2.Second I am thinking of dynamic programming where I can store XOR of already calculated subsequence but I am not able to complete the algorithm.
Can someone please tell some other way of solving this problem.