Largest Multiple of Three - Problem
The Challenge: Building the Largest Multiple of Three
You're given an array of single digits (0-9) and need to construct the largest possible number that is divisible by 3 using any subset of these digits.
🎯 Goal: Form the largest multiple of 3 by concatenating digits in any order
📥 Input: Array of digits [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
📤 Output: String representing the largest multiple of 3 (or empty string if impossible)
Key Rules:
• Use any subset of the given digits
• Arrange them to form the largest possible number
• Result must be divisible by 3
• No leading zeros (except for "0")
• Return as string to handle large numbers
Example: For digits [8, 1, 9], you can form "981" (9+8+1=18, divisible by 3)
You're given an array of single digits (0-9) and need to construct the largest possible number that is divisible by 3 using any subset of these digits.
🎯 Goal: Form the largest multiple of 3 by concatenating digits in any order
📥 Input: Array of digits [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
📤 Output: String representing the largest multiple of 3 (or empty string if impossible)
Key Rules:
• Use any subset of the given digits
• Arrange them to form the largest possible number
• Result must be divisible by 3
• No leading zeros (except for "0")
• Return as string to handle large numbers
Example: For digits [8, 1, 9], you can form "981" (9+8+1=18, divisible by 3)
Input & Output
example_1.py — Basic Case
$
Input:
[8,1,9]
›
Output:
"981"
💡 Note:
The sum 8+1+9=18 is divisible by 3. Arranging in descending order gives us 981, which is the largest possible multiple of 3.
example_2.py — Need to Remove Digits
$
Input:
[8,6,7,1,0]
›
Output:
"8760"
💡 Note:
Sum is 22, remainder is 1. We remove the smallest digit with remainder 1 (which is 1), leaving [8,6,7,0]. Arranging gives 8760.
example_3.py — All Zeros Case
$
Input:
[0,0,0,0]
›
Output:
"0"
💡 Note:
All digits are zero, so the largest (and only) multiple of 3 we can form is "0" (not "0000" to avoid leading zeros).
Constraints
- 1 ≤ digits.length ≤ 104
- 0 ≤ digits[i] ≤ 9
- The answer may not fit in a 32-bit integer, so return it as a string
- No leading zeros in the result (except for the result "0")
Visualization
Tap to expand
Understanding the Visualization
1
Sort Coins by Type
Group your digit-coins by their remainder when divided by 3 (types 0, 1, and 2)
2
Check Total Value
Add up all coin values and see if the sum is divisible by 3
3
Remove Minimal Coins
If not divisible, remove the fewest, lowest-value coins to make it work
4
Arrange for Maximum
Sort remaining coins from highest to lowest value to maximize the final amount
Key Takeaway
🎯 Key Insight: Use the divisibility rule for 3 (sum of digits) combined with modular arithmetic to efficiently determine which digits to keep, then arrange them for maximum value.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code