Longest subsequence with different adjacent characters | dp table ; A recursive function to find the update the dp [ ] [ ] table ; If we reach end of the String ; If subproblem has been computed ; Initialise variable to find the maximum length ; Choose the current character ; Omit the current character ; Return the store answer to the current subproblem ; Function to find the longest Subsequence with different adjacent character ; Length of the String s ; Initialise the memoisation table ; Return the final ans after every recursive call ; Driver Code ; Function call
let dp = new Array ( 100005 ) ; function calculate ( pos , prev , s ) { if ( pos == s . length ) { return 0 ; } if ( dp [ pos ] [ prev ] != - 1 ) return dp [ pos ] [ prev ] ; let val = 0 ; if ( s [ pos ] . charCodeAt ( ) - ' ' . charCodeAt ( ) + 1 != prev ) { val = Math . max ( val , 1 + calculate ( pos + 1 , s [ pos ] . charCodeAt ( ) - ' ' . charCodeAt ( ) + 1 , s ) ) ; } val = Math . max ( val , calculate ( pos + 1 , prev , s ) ) ; dp [ pos ] [ prev ] = val ; return dp [ pos ] [ prev ] ; } function longestSubsequence ( s ) { let n = s . length ; for ( let i = 0 ; i < 100005 ; i ++ ) { dp [ i ] = new Array ( 27 ) ; for ( let j = 0 ; j < 27 ; j ++ ) { dp [ i ] [ j ] = - 1 ; } } return calculate ( 0 , 0 , s ) ; } let str = " " ; document . write ( longestSubsequence ( str ) ) ;