DOJ logoDOJ
Problems
Recently added problemsSaved problems
CategoriesDLCContestsGroupsTeamsBoard
Ranking
Solved Problem RankingStreak rankingDOJ Power ranking
Status
Call for TasksLoginRegister
DOJ logoDOJ

Community online judge with OI-style subtask scoring, Elo ratings, and Discord-backed certification.

Problems
ProblemsCategories
Community
ContestsRankingBoardNoticesHost an external contestGuide
Account
LoginRegisterJudge Status
Policy
Terms of ServiceDLC RulesPrivacyAPI documentationLanguage runtimesContest rank rewardsRating and performance
© 2026 DOJ
All rights reserved
Editorial

Overlapping Intervals

Back to problem

Editorial

Use 000-based indices in this explanation.

Suppose the left endpoints of two consecutive currently open intervals are a<ba<ba<b. We first have to close the interval that starts at aaa, and then choose the left endpoint of the next interval.

Let dp⁡[a][b]\operatorname{dp}[a][b]dp[a][b] be the maximum number of intervals obtainable from a chain whose first two left endpoints are aaa and bbb. Its value is 000 if such a chain cannot be completed.

Let ccc be the first position after bbb such that Sc=SaS_c=S_aSc​=Sa​. 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 SbS_bSb​ after ccc. Otherwise, to create at least three intervals, choose a new left endpoint d>cd>cd>c. The remaining problem is exactly the state (b,d)(b,d), so

dp⁡[a][b]=max⁡(2, 1+max⁡d>cdp⁡[b][d]).\operatorname{dp}[a][b]=\max\left(2,\ 1+\max_{d>c}\operatorname{dp}[b][d]\right).dp[a][b]=max(2, 1+d>c

The first term is available only when an occurrence of SbS_bSb​ exists after ccc, and the second term is available only when a positive state exists in the range.

Maintain

suf⁡[b][x]=max⁡d≥xdp⁡[b][d].\operatorname{suf}[b][x]=\max_{d\ge x}\operatorname{dp}[b][d].suf[b][x]=d≥xmax​dp[b][d].

Then every transition takes O(1)O(1)O(1) time. Since dp⁡[a][b]\operatorname{dp}[a][b]dp[a][b] only refers to states dp⁡[b][d]\operatorname{dp}[b][d]dp[b][d] with a<b<da<b<d, process in decreasing order.

Take the maximum over all states. Separately handle the answer 111 by checking whether any character occurs at least twice. The total time complexity is O(N2)O(N^2)O(N2) and the memory complexity is O(N2)O(N^2)O(N2).

Solution written by GPT5.6

dp⁡[a][b]=0\operatorname{dp}[a][b]=0
dp[a][b]=0
ccc
ccc
(
b
,
d
)
max
​
dp
[
b
]
[
d
]
)
.
a<
b<
d
aaa