Stones ------ In general, when you see "longest subsequence" problems, you should think dynamic programming; this may not always be the case, but most of the time it is, and it certainly is here. Dynamic programming works for problems for which an optimal solution has parts that are themselves optimal. In this case, we can iterate through the string character by character, and consider how each new character may improve the best result. If the character under consideration is a 3, then we can either add it to a previously seen long string that has not yet had a 3 added to it, or we can add it to a previously seen long string that ends in 3. Indeed, we do not even need to remember the strings themselves; all we need to remember is, for each combination of sets of characters that have been used so far, and ending character, what the longest string so far is. With only five possible characters, only 2^5 or 32 sets of characters are possible. We represent each set by a simple int, with bit position b representing the inclusion of character c. So the final code looks like this: int nsets = 1<