Largest Multiple of Three - Problem

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.

Note: The answer may not fit in an integer data type, so return the answer as a string. The returning answer must not contain unnecessary leading zeros.

Input & Output

Example 1 — Basic Case
$ Input: digits = [8,1,9]
Output: 981
💡 Note: Sum = 8+1+9 = 18, which is divisible by 3. Use all digits arranged in descending order to get the largest number: 981.
Example 2 — Need to Remove Digits
$ Input: digits = [8,6,7,1,0]
Output: 8760
💡 Note: Sum = 22, remainder = 1. Remove the smallest digit with remainder 1 (which is 1). Remaining digits [8,6,7,0] sum to 21, divisible by 3. Result: 8760.
Example 3 — All Zeros Case
$ Input: digits = [0,0,0]
Output: 0
💡 Note: Sum = 0, divisible by 3. All digits are zero, so return single '0' to avoid leading zeros.

Constraints

  • 1 ≤ digits.length ≤ 104
  • 0 ≤ digits[i] ≤ 9

Visualization

Tap to expand
Largest Multiple of Three INPUT digits array: 8 [0] 1 [1] 9 [2] Sum of digits: 8 + 1 + 9 = 18 18 % 3 = 0 Divisible by 3! Remainders when / 3: 8%3=2, 1%3=1, 9%3=0 rem0:[9] rem1:[1] rem2:[8] ALGORITHM STEPS 1 Calculate Sum Sum = 18, check 18 % 3 2 Check Remainder rem=0: Use all digits 3 Sort Descending For largest number 4 Concatenate Join sorted digits Sorting Process: [8, 1, 9] --> [9, 8, 1] descending order Greedy Decision: Sum%3=0: Keep all digits No removal needed FINAL RESULT Sorted digits concatenated: 9 8 1 Output: 981 Verification: 981 / 3 = 327 OK Largest multiple of 3 using digits [8,1,9] Key Insight: A number is divisible by 3 if the sum of its digits is divisible by 3. The greedy approach removes minimum digits to make sum%3=0, then sorts remaining digits in descending order for the largest possible number. If sum%3=1, remove one digit with rem=1 or two with rem=2. TutorialsPoint - Largest Multiple of Three | Greedy - Mathematical Approach
Asked in
Google 45 Amazon 38 Microsoft 32 Apple 25
42.0K Views
Medium Frequency
~25 min Avg. Time
894 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen