Remove some digits and re-order the digits (if necessary) so that the resulting integer would be the maximum possible integer that is divisible by 3.

algorithmselementary-number-theoryprogramming

Given an integer. The task is to remove some digits and re-order the digits (if necessary) so that the resulting integer would be the maximum possible integer that is divisible by 3.

I am having some difficulties to think of an algorithm to implement it in code.

  1. If the number is itself divisible by 3 then just print the digits in descending order.

  2. If the number is 1 modulo 3 then remove one the smallest digit in the integer that is also 1 modulo 3 then just print the digits in descending order. If there is no such a digit then remove two smallest digits that are 2 modulo 3 then just print the digits in descending order. If there are no such digits neither then it is impossible to complete the task.

  3. If the number is 2 modulo 3 then something similar to the case 2 above.

I was wondering if this algorithm is correct and optimal. Thanks in advance for your help.

Best Answer

You seem to be assuming that the integer is positive and that it’s written in decimal notation. If so, the algorithm is correct and optimal. The case where you write “it is impossible to complete the task” can’t occur, because the number can’t have residue $1$ modulo $3$ unless it contains either at least one digit with residue $1$ or at least two digits with residue $2$.

A problem that can occur, though, is that there are no digits left after you’ve removed some digits. In that case, it is indeed impossible to complete the task (unless we allow the empty digit string to represent $0$).

Related Question