Don’t be intimidated by the official solution.
Solution #
First let’s introduce “sorted subsequence”: a sorted subsequence is a subsequence that is a subarray of the sorted array. It’s easy to see that the unmoved elements form a sorted subsequence. So if we find the longest sorted subsequence, the answer is minimized.
Since we only care about the relative order of numbers, we can compress the number which makes it easier to program. Then for each number we make an array storing all the indices of this number.
Now let’s iterate over each number. If the smallest index of the current number is greater than the biggest index of the previous number, we can simply add all the index to our subsequence. Otherwise, we need to start a new subsequence. There are two things we should notice:
-
Part of the indices of the current number can be added to the old subsequence. E.g.
1,2,1,1,2
, the second 2 can be added so we have1,1,1,2
. -
The new subsequence can also include part of the indices of the previous number. E.g.
1,2,2,1,2
we can add the first 1 to the front so we have1,2,2,2
.
There is one special case: the subsequence consists indices of two numbers and indices of both numbers are incomplete. E.g. 2,1,1,2,2,1
, it’s easy to see that we need a prefix of the fist number the a suffix of the second number. So we can iterate over each prefix of the first number and find the corresponding suffix of the second number.