![]() |
VOOZH | about |
Given an input string S, the task is to make it a palindrome and calculate the minimum cost for making it a palindrome, where you are allowed to use any one of the following operations any number of times:
Examples:
Input: S = "moon"
Output: 1
Explanation: We need to make 'm' = = 'n' then the input string will become palindrome. So, the cost will be the ASCII value of 'n' - ASCII value of 'm' i.e. 1.Input: S = "zone"
Output: 11
Explanation: We need to make 'z' == 'e' and the absolute difference between their ASCII values is 21. So we replace both characters with 'a' and it will cost 10 which is more efficient than 21 and for making 'o' == 'n' the cost will be 1. Total cost = 10 + 1 .
Approach: This can be solved with the following idea:
For every pair of characters choose whether their ASCII difference gives an optimized answer or replacing them with 'a' gives the optimized answer.
Below are the steps involved in the implementation of the code:
Below is the implementation of the above-mentioned approach in C++:
1
Time Complexity: O(N)
Auxiliary Space: O(1)