Length of the longest subsequence such that XOR of adjacent elements is equal to K | Java program for above approach ; Function to find maximum length of subsequence ; Stores maximum length of subsequence ; HashMap to store the longest length of subsequence ending at an integer , say X ; Stores the maximum length of subsequence ending at index i ; Base case ; Iterate over the range [ 1 , N - 1 ] ; Retrieve the longest length of subsequence ending at integer a [ ] ^ K ; If dpj is not NULL ; Update dp [ i ] ; Update ans ; Update the maximum length of subsequence ending at element is a [ i ] in HashMap ; Return the ans if ans >= 2. Otherwise , return 0 ; Driver Code ; Input ; Print the length of the longest subsequence
import java . io . * ; import java . util . * ; class GFG { public static int xorSubsequence ( int a [ ] , int n , int k ) { int ans = 0 ; HashMap < Integer , Integer > map = new HashMap < > ( ) ; int dp [ ] = new int [ n ] ; map . put ( a [ 0 ] , 1 ) ; dp [ 0 ] = 1 ; for ( int i = 1 ; i < n ; i ++ ) { Integer dpj = map . get ( a [ i ] ^ k ) ; if ( dpj != null ) dp [ i ] = Math . max ( dp [ i ] , dpj + 1 ) ; ans = Math . max ( ans , dp [ i ] ) ; map . put ( a [ i ] , Math . max ( map . getOrDefault ( a [ i ] , 1 ) , dp [ i ] ) ) ; } return ans >= 2 ? ans : 0 ; } public static void main ( String [ ] args ) { int arr [ ] = { 3 , 2 , 4 , 3 , 5 } ; int N = arr . length ; int K = 1 ; System . out . println ( xorSubsequence ( arr , N , K ) ) ; } }