DOJ logoDOJ
Problems
Recently added problemsSaved problemsWorkbooks
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 account linking.

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

67

Back to problem

Editorial

Run dynamic programming separately for m=6m=6m=6 and m=7m=7m=7. Let dpm[r]dp_m[r]dpm​[r] be the maximum length of a nonempty subsequence among the digits processed so far whose remainder modulo mmm is rrr. A value of 000 means that no such subsequence exists.

For the next digit ddd, either skip it, start a new one-digit number, or append it to an existing subsequence. Appending to a subsequence with remainder rrr gives remainder (10r+d) mod m(10r+d)\bmod m(10r+d)modm. Use only states from before processing the digit for these transitions.

After processing all digits, let L=max⁡(dp6[0],dp7[0])L=\max(dp_6[0],dp_7[0])L=max(dp6​[0],dp7​[0]). If , print . Otherwise, print . Each case takes time and auxiliary space, excluding the input string.

Proof

Initially, no nonempty subsequence exists, so all states are 000. After processing the next digit, every possible subsequence either omits it, consists of that digit alone, or appends it to a previous subsequence. The transitions take the maximum over exactly these possibilities, so each state has its claimed maximum length.

A valid number has remainder 000 modulo 666 or modulo 777. Thus LLL is the maximum number of characters that can remain, and N is the minimum number to delete. If , no nonempty valid subsequence exists.

For subtask 1, enumerate all nonempty subsequences in O(N2N)O(N2^N)O(N2N) time. For subtask 2, use the position of the last selected digit and the remainder as the state, and transition from every earlier position in O(N2)O(N^2)O(N2) time. For the full constraints, keep only the maximum length for each remainder.

Solution written by GPT6

L=0L=0
L=0
−1-1−1
N−LN-LN−L
O(N)O(N)O(N)
O(1)O(1)O(1)
−LN-L
N−L
L=0L=0L=0