Minimum replacements to make adjacent characters unequal in a ternary string | Set | function to return integer value of i - th character in the string ; Function to count the number of minimal replacements ; If the string has reached the end ; If the state has been visited previously ; Get the current value of character ; If it is equal then change it ; All possible changes ; Change done ; } else If same no change ; Driver Code ; Length of string ; Create a DP array ; First character ; Function to find minimal replacements
function charVal ( s , i ) { if ( s . charAt ( i ) == ' ' ) { return 0 ; } else if ( s . charAt ( i ) == ' ' ) { return 1 ; } else { return 2 ; } } function countMinimalReplacements ( s , i , prev , dp , n ) { if ( i == n ) { return 0 ; } if ( dp [ i ] [ prev ] != - 1 ) { return dp [ i ] [ prev ] ; } var val = charVal ( s , i ) ; var ans = Number . MAX_VALUE ; if ( val == prev ) { val = 0 ; for ( var cur = 0 ; cur <= 2 ; cur ++ ) { if ( cur == prev ) { continue ; } val = 1 + countMinimalReplacements ( s , i + 1 , cur , dp , n ) ; ans = Math . min ( ans , val ) ; } { ans = countMinimalReplacements ( s , i + 1 , val , dp , n ) ; } return dp [ i ] [ val ] = ans ; } var s = " " ; var n = s . length ; var dp = Array ( n ) . fill ( ) . map ( ( ) => Array ( 3 ) . fill ( 0 ) ) ; for ( var i = 0 ; i < n ; i ++ ) { for ( var j = 0 ; j < 3 ; j ++ ) { dp [ i ] [ j ] = - 1 ; } } var val = charVal ( s , 0 ) ; document . write ( countMinimalReplacements ( s , 1 , val , dp , n ) ) ;