Minimize cost to convert given string to a palindrome | Function to find the minimum cost to convert the into a palindrome ; Length of the string ; If iointer is in the second half ; Reverse the string ; 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 palindrome ; min distance to travel to make palindrome ; Total cost ; Return the minimum cost ; Driver Code ; Given S ; Given pointer P ; Function Call
def findMinCost ( strr , pos ) : NEW_LINE INDENT n = len ( strr ) NEW_LINE if ( pos >= n / 2 ) : NEW_LINE INDENT strr = strr [ : : - 1 ] NEW_LINE pos = n - pos - 1 NEW_LINE DEDENT left , right = pos , pos NEW_LINE for i in range ( pos , - 1 , - 1 ) : NEW_LINE INDENT if ( strr [ i ] != strr [ n - i - 1 ] ) : NEW_LINE INDENT left = i NEW_LINE DEDENT DEDENT for i in range ( pos , n // 2 ) : NEW_LINE INDENT if ( strr [ i ] != strr [ n - i - 1 ] ) : NEW_LINE INDENT right = i NEW_LINE DEDENT DEDENT ans = 0 NEW_LINE for i in range ( left , right + 1 ) : NEW_LINE INDENT if ( strr [ i ] != strr [ n - i - 1 ] ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT DEDENT dis = ( min ( ( 2 * ( pos - left ) + ( right - pos ) ) , ( 2 * ( right - pos ) + ( pos - left ) ) ) ) NEW_LINE ans = ans + dis NEW_LINE return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = " bass " NEW_LINE P = 3 NEW_LINE print ( findMinCost ( S , P ) ) NEW_LINE DEDENT