This problem can be recounted as:
What is the minimum number of moves to convert a string S to a string containing only 'a'?
Definition
Consider a continuous subsequence as a sequence of identical characters in a string. The smallest contiguous subsequence is naturally the only symbol. If you normalize small subsequences, you naturally get large subsequences, eventually getting one subsequence - the whole line.
What is normalized for :
Only the UP or DOWN character can be moved, so the character itself is a sequence of UP and DOWN steps. The worst case of representing a character is a letter in the middle of the alphabet, which requires at least len(alphabet) / 2 movement. In the alphabet {a..z} worst are 'm' and 'n' .
Since we want to minimize the number of moves, we need to pull out the letters DOWN C <= m and pull them out C >= n . Thus, in order to minimize the normalization process, we must find the largest subsequences that require equal normalization moves. For example, if we have a goal zzzzbzzzz , we know that the minimum directions of UUUUDUUUU are U for UP and D, DOWN.
Normalization
For each movement, the counter is incremented, which gives the least number of moves needed to convert the string. Given the above example, we can take the following steps:
Another example, with the target string abcxyz :
EDIT
As @ user1884905 pointed out, this solution , as suggested, is not optimal . In the case of the target string mn algorithm does not lead to an optimal solution:
And this is not optimal, since the following steps require less moves:
#0 #1 #2 ... #12 mn -> mm -> ll -> ... -> aa
Perhaps the optimal substructure of the greedy algorithm is to reduce the global distance between characters from the string, instead of focusing on the difference between such characters and the base case ( 'a' ).