Largest Multiple of Three Problem
Description
LeetCode Problem 1363.
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 <= 10^40 <= digits[i] <= 9
Solution
Approach: Greedy Removal by Remainder
A number is a multiple of 3 exactly when its digit sum is. So the question is which digits to leave out: once the set of digits is chosen, the largest number is those digits sorted from 9 down to 0.
A longer number beats a shorter one, so we want to drop as few digits as possible. Let r = sum(digits) % 3:
r == 0: keep everything.r == 1: dropping one digit with remainder 1 (a 1, 4 or 7) fixes the sum. If there is none, drop two digits with remainder 2 (2, 5 or 8), since 2 + 2 = 4 has remainder 1.r == 2: symmetric: drop one digit with remainder 2, or else two digits with remainder 1.
Among removals of the same size, drop the smallest suitable digits: the kept digits are then as large as possible, and the sorted result is largest.
The fallback never fails: if r == 1 and there is no digit with remainder 1, the sum's remainder comes only from the digits with remainder 2, so there must be at least two of them (one would give remainder 2, not 1). The same holds for r == 2. The fallback may remove everything, as in [2, 2], and then the answer is "".
Count the digits 0 to 9 instead of sorting, do the removals on the counts, and write the digits from 9 down to 0. The last tricky case is zeros: if the result starts with 0, every kept digit is 0 ([0, 0, 0], or [1, 0, 0, 0] after dropping the 1), and the answer must be "0", not "000".
Complexity: O(n) time to count and to build the answer, and O(1) extra space besides the output string.
class Solution:
def largestMultipleOfThree(self, digits: List[int]) -> str:
count = [0] * 10
for d in digits:
count[d] += 1
def drop(residue: int, k: int) -> bool:
"""Remove the k smallest digits that are = residue (mod 3); report success."""
for d in range(residue, 10, 3):
while count[d] > 0 and k > 0:
count[d] -= 1
k -= 1
return k == 0
r = sum(digits) % 3
if r != 0 and not drop(r, 1): # best: drop one digit with the same remainder
drop(3 - r, 2) # otherwise two digits with the other remainder (always possible)
ans = "".join(str(d) * count[d] for d in range(9, -1, -1))
return "0" if ans.startswith("0") else ans # only zeros left: answer "0"