1363. Largest Multiple of Three
Given an array of digits digits, return the largest multiple of three that can be formed by concatenating some of the given digits in any order. If there is no answer return an empty string.
Since the answer may not fit in an integer data type, return the answer as a string. Note that the returning answer must not contain unnecessary leading zeros.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 class Solution { string solve (unordered_map<int ,int >& cnt) { string res; for (int i = 9 ; i >= 0 ; i--) { if (!cnt[i]) continue ; res += string (cnt[i], i | 0b110000 ); } return cnt[0 ] and res.length () == cnt[0 ] ? "0" : res; } public : string largestMultipleOfThree (vector<int >& digits) { int sum = 0 ; unordered_map<int , int > cnt; for (auto & d : digits) { sum += d; cnt[d]++; } int remainder = sum % 3 ; if (remainder == 0 ) return solve (cnt); if (remainder == 1 ) { if (cnt[1 ]) {cnt[1 ]--; return solve (cnt);} if (cnt[4 ]) {cnt[4 ]--; return solve (cnt);} if (cnt[7 ]) {cnt[7 ]--; return solve (cnt);} if (cnt[2 ] >= 2 ) {cnt[2 ] -= 2 ; return solve (cnt); } if (cnt[2 ] and cnt[5 ]) {cnt[2 ]--; cnt[5 ]--; return solve (cnt);} if (cnt[5 ] >= 2 ) {cnt[5 ] -= 2 ; return solve (cnt); } if (cnt[2 ] and cnt[8 ]) {cnt[2 ]--; cnt[8 ]--; return solve (cnt);} if (cnt[5 ] and cnt[8 ]) {cnt[5 ]--; cnt[8 ]--; return solve (cnt);} if (cnt[8 ] >= 2 ) {cnt[8 ] -= 2 ; return solve (cnt); } return "" ; } if (cnt[2 ]) {cnt[2 ]--; return solve (cnt);} if (cnt[5 ]) {cnt[5 ]--; return solve (cnt);} if (cnt[8 ]) {cnt[8 ]--; return solve (cnt);} if (cnt[1 ] >= 2 ) {cnt[1 ] -= 2 ; return solve (cnt); } if (cnt[1 ] and cnt[4 ]) {cnt[1 ]--; cnt[4 ]--; return solve (cnt);} if (cnt[4 ] >= 2 ) {cnt[4 ] -= 2 ; return solve (cnt); } if (cnt[1 ] and cnt[7 ]) {cnt[1 ]--; cnt[7 ]--; return solve (cnt);} if (cnt[4 ] and cnt[7 ]) {cnt[4 ]--; cnt[7 ]--; return solve (cnt);} if (cnt[7 ] >= 2 ) {cnt[7 ] -= 2 ; return solve (cnt); } return "" ; } };