Length of the longest subsequence such that XOR of adjacent elements is equal to K | C # program for above approach ; Function to find maximum length of subsequence ; Stores maximum length of subsequence ; Dictionary 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 Dictionary ; Return the ans if ans >= 2. Otherwise , return 0 ; Driver Code ; Input ; Print the length of the longest subsequence
using System ; using System . Collections . Generic ; public class GFG { public static int xorSubsequence ( int [ ] a , int n , int k ) { int ans = 0 ; Dictionary < int , int > map = new Dictionary < int , int > ( ) ; int [ ] dp = new int [ n ] ; map . Add ( a [ 0 ] , 1 ) ; dp [ 0 ] = 1 ; for ( int i = 1 ; i < n ; i ++ ) { int dpj = map . ContainsKey ( a [ i ] ^ k ) ? map [ a [ i ] ^ k ] : - 1 ; if ( dpj != 0 ) dp [ i ] = Math . Max ( dp [ i ] , dpj + 1 ) ; ans = Math . Max ( ans , dp [ i ] ) ; if ( map . ContainsKey ( a [ i ] ) ) { map [ a [ i ] ] = Math . Max ( map [ a [ i ] ] + 1 , dp [ i ] ) ; ; } else { map . Add ( a [ 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 N = arr . Length ; int K = 1 ; Console . WriteLine ( xorSubsequence ( arr , N , K ) ) ; } }