Editorial
Run dynamic programming separately for and . Let be the maximum length of a nonempty subsequence among the digits processed so far whose remainder modulo is . A value of means that no such subsequence exists.
For the next digit , either skip it, start a new one-digit number, or append it to an existing subsequence. Appending to a subsequence with remainder gives remainder . Use only states from before processing the digit for these transitions.
After processing all digits, let . 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 . 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 modulo or modulo . Thus is the maximum number of characters that can remain, and is the minimum number to delete. If , no nonempty valid subsequence exists.
For subtask 1, enumerate all nonempty subsequences in 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 time. For the full constraints, keep only the maximum length for each remainder.
Solution written by GPT6