1363. Largest Multiple of Three
Description
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.
Example 1:
Input: digits = [8,1,9] Output: "981"
Example 2:
Input: digits = [8,6,7,1,0] Output: "8760"
Example 3:
Input: digits = [1] Output: ""
Constraints:
1 <= digits.length <= 104
0 <= digits[i] <= 9
Solutions
Solution: Greedy
- Time complexity: O(n)
- Space complexity: O(10 -> 1)
JavaScript
js
/**
* @param {number[]} digits
* @return {string}
*/
const largestMultipleOfThree = function (digits) {
const mod1 = [1, 4, 7, 2, 5, 8];
const mod2 = [2, 5, 8, 1, 4, 7];
const counts = Array.from({ length: 10 }, () => 0);
let sum = digits.reduce((result, digit) => result + digit);
for (const digit of digits) {
counts[digit] += 1;
}
while (sum % 3) {
const mod = sum % 3 === 1 ? mod1 : mod2;
const removeDigit = mod.find(digit => counts[digit]);
counts[removeDigit] -= 1;
sum -= removeDigit;
}
let result = '';
for (let digit = 9; digit >= 0; digit--) {
result += `${digit}`.repeat(counts[digit]);
}
return result[0] === '0' ? '0' : result;
};