Editorial
Use -based indices in this explanation.
Suppose the left endpoints of two consecutive currently open intervals are . We first have to close the interval that starts at , and then choose the left endpoint of the next interval.
Let be the maximum number of intervals obtainable from a chain whose first two left endpoints are and . Its value is if such a chain cannot be completed.
Let be the first position after such that . If no such position exists, then . Choosing a later occurrence instead of only removes positions that could be used later, so considering the earliest such is sufficient.
The chain can end with exactly two intervals if there is an occurrence of after . Otherwise, to create at least three intervals, choose a new left endpoint . The remaining problem is exactly the state , so
The first term is available only when an occurrence of exists after , and the second term is available only when a positive state exists in the range.
Maintain
Then every transition takes time. Since only refers to states with , process in decreasing order.
Take the maximum over all states. Separately handle the answer by checking whether any character occurs at least twice. The total time complexity is and the memory complexity is .
Solution written by GPT5.6