Editorial
Suppose a value appears times in the sequence. Since every deleted segment must have pairwise distinct elements, one operation cannot delete two or more occurrences of .
Therefore, to delete one occurrence of , the same operation must also delete at least one element different from . There are only elements different from , so at most occurrences of can be deleted. Hence at least
occurrences of must remain.
Taking the maximum over all values, if is the maximum frequency of any value, the answer is at least
We now show that this lower bound is always achievable.
First, suppose . Let be a most frequent value. As long as there is an element different from , there must be an adjacent pair consisting of one and one non- element. These two elements are distinct, so we can delete this segment of length . Repeating this removes all non- elements and the same number of elements. Thus exactly elements remain.
Now suppose . We claim that all elements can be deleted. This can be proved by induction on the current length of the sequence.
Let the current length be and let be the current maximum frequency.
- If , the two elements must be distinct, so they can be deleted at once.
- If the maximum frequency is small enough, deleting any adjacent unequal pair keeps every frequency at most half of the new length, so the induction hypothesis applies.
- If a value has frequency close to half, there is a boundary where that value is adjacent to a different value. Deleting this pair decreases the critical frequency.
- The only delicate case is when is odd and two different values each appear times. If those two values are adjacent, delete that adjacent pair. Otherwise, the single remaining value lies between them somewhere, so there is a segment of length containing three pairwise distinct values. Delete that segment. In both cases, the induction hypothesis applies afterward.
Therefore, when , the whole sequence can be deleted.
Hence the answer is
where is the maximum frequency of any value.
The implementation only needs to count frequencies and find the maximum one.
The time complexity is .