Since this is just some additional info and maybe some optimization, this should be a comment to the answer of Rubens, but in an answer I can explain it better and it can be useful for the questioner too.
I also use the great reverse idea of Rubens.
So, I think there's no situation when it is necessary to rotate an a
to something else. If this is correct (I have no counterexample), there is no situation where we should rotate something to the wrong direction ( I have no mathematican proof, but probably this is correct).
So, every subsequences of U
s and D
s will be rotated each time with one motion. This algorithm won't take O(n^2) time. Here is the algorithm:
Let we call Rubens's string direction string
- set a counter to 0
- compute the direction string
- scan the direction string.
- if You find a contigous subsequence of U or D letters, rotate the target string at the positions towards
a
and increment the counter(once for each subsequence).
- if there was any operation, go back to step 2
This algorithm will rotate every wheel to a
and it will be done after at most k/2
scanning, where k
is the count of the elements of the alphabet, so this may be a solution that runs in linear time.
Maybe there is a solution with even less operation. It is just an idea, with finding increasing, decreasing or "hill-shape" sub-subsequences and extract the maximum value.For example: We can say without computing, that the cost of solving
is equal to the cost of solving a single e
EDIT: I've seen user1884905's counterexample. So my algorithm will not find the optimal solution, but it can be usable to find the correct algorithm, so I don't delete it yet.
EDIT 2: Another idea that works with the sample target strings: There could be computed an average letter. It is the one for which the sum of the distances from the target string's letters is minimal. Every letter should be rotated here with the algorithm above, then the whole string can be rotated to aaaaaaaaaa
. Since the alphabet is cyclic, there could be more than one average letter( like in the second example in the question), in this case we should chose the one with the minimal distance from a
.