We are asked to modify a string by performing specific moves on it. Given a string of lowercase English characters ('a' - 'z'), two types of moves can be performed on any index, any number of times:
- Decrement the character by 1. The letter 'a' cannot be decremented.
- Increment the character by 1. Letter 'z' cannot be incremented.
Calculate the minimum number of moves required to modify the string to a good form. A good form string is one in which each character is adjacent to at least one equal character.
Example 1:
s = ‘aca’
Output: 2
Explanation: Decrement 'c' twice to get 'aaa'. A minimum of 2 moves is required.
Example 2:
s = 'abcdef'
Output: 3
Explanation: Decrement 'b' by 1 to become 'a'. Increment 'c' by 1 to become 'd'. Increment 'e' by 1 to become 'f'. This gets us "aaddff".
The first and last characters of the string only have one adjacent neighbor, and so they must be equal to that adjacent character.
What would be the best way to go about this?
I initially thought using two pointers, one for the left/start and right/end indices, and slowly moving them towards the center would be the best approach, using the thought that the edge of the string must be equal to the inner character in order to become equal.
But this doesn't give us a globally optimal solution. Would the best approach be something related to dynamic programming? If so, how would that look?