Minimize cost to convert given string to a palindrome | Function to find the minimum cost to convert the string into a palindrome ; Length of the string ; If iointer is in the second half ; Reverse the string ; Pointing to initial position ; Find the farthest index needed to change on left side ; Find the farthest index needed to change on right side ; Changing the variable to make string palindrome ; min distance to travel to make string palindrome ; Total cost ; Return the minimum cost ; Given string S ; Given pointer P ; Function Call
function findMinCost ( str , pos ) { var n = str . length ; if ( pos >= n / 2 ) { str . split ( ' ' ) . reverse ( ) . fill ( ' ' ) ; pos = n - pos - 1 ; } var left , right ; left = right = pos ; for ( var i = pos ; i >= 0 ; -- i ) { if ( str [ i ] != str [ n - i - 1 ] ) { left = i ; } } for ( var i = pos ; i < n / 2 ; ++ i ) { if ( str [ i ] != str [ n - i - 1 ] ) { right = i ; } } var ans = 0 ; for ( var i = left ; i <= right ; ++ i ) { if ( str [ i ] != str [ n - i - 1 ] ) ans += 1 ; } var dis = Math . min ( ( 2 * ( pos - left ) + ( right - pos ) ) , ( 2 * ( right - pos ) + ( pos - left ) ) ) ; ans = ans + dis ; return ans ; } var S = " " ; var P = 3 ; document . write ( findMinCost ( S , P ) ) ;