Length of the longest subsequence such that XOR of adjacent elements is equal to K | Java program for the above approach ; Function to find maximum length of subsequence having XOR of adjacent elements equal to K ; Store maximum length of subsequence ; Stores the dp - states ; Base case ; Iterate over the range [ 1 , N - 1 ] ; Iterate over the range [ 0 , i - 1 ] ; If arr [ i ] ^ arr [ j ] = = K ; Update the dp [ i ] ; Update the maximum subsequence length ; If length of longest subsequence is less than 2 then return 0 ; Driver Code ; Input ; Print the length of longest subsequence
import java . io . * ; import java . util . * ; class GFG { public static int xorSubsequence ( int a [ ] , int n , int k ) { int ans = 0 ; int dp [ ] = new int [ n ] ; dp [ 0 ] = 1 ; for ( int i = 1 ; i < n ; i ++ ) { for ( int j = i - 1 ; j >= 0 ; j -- ) { if ( ( a [ i ] ^ a [ j ] ) == k ) dp [ i ] = Math . max ( dp [ i ] , dp [ j ] + 1 ) ; } ans = Math . max ( ans , dp [ i ] ) ; dp [ i ] = Math . max ( 1 , dp [ i ] ) ; } return ans >= 2 ? ans : 0 ; } public static void main ( String [ ] args ) { int arr [ ] = { 3 , 2 , 4 , 3 , 5 } ; int K = 1 ; int N = arr . length ; System . out . println ( xorSubsequence ( arr , N , K ) ) ; } }