#K93297. Largest Permutation Divisible by 3
Largest Permutation Divisible by 3
Largest Permutation Divisible by 3
You are given a string s
consisting of digits (0-9). Your task is to rearrange the digits to form the largest possible permutation such that the resulting number is divisible by 3. If no permutation of the digits results in a number divisible by 3, output NO
.
Recall that a number is divisible by 3 if and only if the sum of its digits is divisible by 3, i.e., if \(\sum_{i=1}^{n} d_i \equiv 0 \pmod{3}\).
Example:
For string "123", the largest permutation is "321" and since \(3+2+1=6\) which is divisible by 3, the output is "321". For string "55", since \(5+5=10\) is not divisible by 3, no arrangement can yield a number divisible by 3, so the output is "NO".
inputFormat
The input is given via standard input (stdin). The first line contains an integer T
representing the number of test cases. Each of the following T
lines contains a string representing a test case.
Example:
3 123 55 102
outputFormat
For each test case, output the largest permutation (as a string) that is divisible by 3. If no such permutation exists, output NO
. Each answer should be printed on a separate line via standard output (stdout).
3
123
55
102
321
NO
210
</p>