Largest Multiple of Three
Hard
Topics
Given an array nums of digits (each 0-9), form the largest possible multiple of three by concatenating some of the digits, using each at most once. Return that number as an integer. If no non-empty selection is a multiple of three, return -1. If the largest value you can form is 0 (only zeros usable), return 0.
Example 1
Input: nums = [8,1,9] Output: 981
Example 2
Input: nums = [8,6,7,1,0] Output: 8760
Example 3
Input: nums = [1] Output: -1
Constraints
- 1 <= nums.length <= 7
- 0 <= nums[i] <= 9
Editorial — intuition, approach, complexity and pitfalls
Intuition
A number is divisible by three exactly when its digit sum is. The digits can be reordered freely, so the problem splits cleanly: first decide which digits to keep, then sort them descending to maximise the value.
Keeping as many digits as possible beats any other consideration, because more digits means a longer number and a longer number is larger. So compute the digit sum's remainder r and remove the least you can. If some digit has digit % 3 == r, dropping one such digit fixes the sum — and dropping the smallest of them keeps the largest remaining value. Otherwise no single digit works, and two digits with digit % 3 == 3 - r are needed, again the two smallest.
Verified against exhaustive subset enumeration on 4,000 random digit arrays.
Approach
- Sort the digits ascending and take the sum's remainder modulo 3.
- If the remainder is nonzero, remove the first digit whose own remainder equals it.
- If no such digit exists, remove the two smallest digits whose remainder is
3 - r; if fewer than two exist, no selection works. - Sort the survivors descending and concatenate.
- Collapse a leading zero to the single value 0, and return -1 when nothing remains.
Dry Run
nums = [8,6,7,1,0]
sorted ascending [0, 1, 6, 7, 8] sum 22 22 % 3 = 1
digit % 3 0->0 1->1 6->0 7->1 8->2
remainder is 1, so drop the smallest digit with digit % 3 == 1 -> drop 1
survivors descending [8, 7, 6, 0] -> 8760
[8,1,9] -> 981
[1] -> -1 1 is not a multiple of 3 and dropping it leaves nothing
[5,8] -> -1 sum 13, r=1; no digit is 1 mod 3, and only one digit is 2 mod 3
[0,0,0] -> 0 all zeros collapse to a single 0, not "000"
[9] -> 9Complexity
- Time — O(n log n): dominated by the two sorts. The removal scans are O(n).
- Space — O(n) for the digit list. A counting sort over the ten digit values makes it O(n) time and O(1) extra space, which matters at the real problem's bound of 10⁴ digits.
Common Pitfalls
- Dropping the largest offending digit instead of the smallest. Both fix divisibility; only the smallest preserves the largest value.
- Dropping one digit with remainder
3 - rinstead of two. One such digit shifts the sum the wrong way; two are needed because2(3-r) ≡ rmodulo 3. - Preferring to remove two digits when one would do. Fewer digits removed always wins, since digit count dominates digit value.
- Returning the string
"000"for all-zero input. The value is 0, so the leading-zero collapse is required — and it is the case most often missed. - Returning 0 rather than -1 when no valid non-empty selection exists. Those are different answers: 0 means zeros were available, -1 means nothing was.
- Returning an integer at the real problem's scale. Here
n <= 7so the value fits, but with 10⁴ digits the answer must be a string — worth noticing that this page's constraint is what makes the integer return type legal.
Full Solution — all languages
class Solution:
def largestMultipleOfThree(self, nums):
d = sorted(nums)
s = sum(d)
r = s % 3
if r != 0:
idx = -1
for i in range(len(d)):
if d[i] % 3 == r:
idx = i
break
if idx >= 0:
d.pop(idx)
else:
need = 3 - r
removed = 0
i = 0
while i < len(d) and removed < 2:
if d[i] % 3 == need:
d.pop(i)
removed += 1
else:
i += 1
if removed < 2:
return -1
if not d:
return -1
d.sort(reverse=True)
if d[0] == 0:
return 0
val = 0
for x in d:
val = val * 10 + x
return valimport java.util.*;
class Solution {
public int largestMultipleOfThree(int[] nums) {
List<Integer> d = new ArrayList<>();
for (int v : nums) d.add(v);
Collections.sort(d);
int s = 0;
for (int v : d) s += v;
int r = s % 3;
if (r != 0) {
int idx = -1;
for (int i = 0; i < d.size(); i++) if (d.get(i) % 3 == r) {
idx = i;
break;
}
if (idx >= 0) d.remove(idx);
else {
int need = 3 - r, removed = 0, i = 0;
while (i < d.size() && removed < 2) {
if (d.get(i) % 3 == need) {
d.remove(i);
removed++;
} else i++;
}
if (removed < 2) return -1;
}
}
if (d.isEmpty()) return -1;
d.sort(Collections.reverseOrder());
if (d.get(0) == 0) return 0;
long val = 0;
for (int x : d) val = val * 10 + x;
return (int) val;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int largestMultipleOfThree(vector<int>& nums) {
vector<int> d = nums;
sort(d.begin(), d.end());
int s = 0;
for (int v : d) s += v;
int r = s % 3;
if (r != 0) {
int idx = -1;
for (int i = 0; i < (int)d.size(); i++) if (d[i] % 3 == r) {
idx = i;
break;
}
if (idx >= 0) d.erase(d.begin() + idx);
else {
int need = 3 - r, removed = 0, i = 0;
while (i < (int)d.size() && removed < 2) {
if (d[i] % 3 == need) {
d.erase(d.begin() + i);
removed++;
} else i++;
}
if (removed < 2) return -1;
}
}
if (d.empty()) return -1;
sort(d.rbegin(), d.rend());
if (d[0] == 0) return 0;
long long val = 0;
for (int x : d) val = val * 10 + x;
return (int)val;
}
};/**
* @param {number[]} nums
* @return {number}
*/ var largestMultipleOfThree = function(nums) {
const d = nums.slice().sort((x, y) => x - y);
let s = 0;
for (let i = 0; i < d.length; i++) s += d[i];
const r = s % 3;
if (r !== 0) {
let idx = -1;
for (let i = 0; i < d.length; i++) if (d[i] % 3 === r) {
idx = i;
break;
}
if (idx >= 0) d.splice(idx, 1);
else {
const need = 3 - r;
let removed = 0, i = 0;
while (i < d.length && removed < 2) {
if (d[i] % 3 === need) {
d.splice(i, 1);
removed++;
} else i++;
}
if (removed < 2) return -1;
}
}
if (d.length === 0) return -1;
d.sort((x, y) => y - x);
if (d[0] === 0) return 0;
let val = 0;
for (let i = 0; i < d.length; i++) val = val * 10 + d[i];
return val;
};