Greatest Sum Divisible by Three - Problem

You're given an array of integers and need to find the maximum possible sum of elements that is divisible by 3.

The key insight is that you don't need to use all elements - you want to select a subset that gives you the largest sum while ensuring the total is divisible by 3.

Example: For array [3,6,5,1,8], you could take 3+6+5+1 = 15 (divisible by 3) or 3+6 = 9 (also divisible by 3). The maximum is 15.

Remember: A number is divisible by 3 if the sum of its digits is divisible by 3. This property extends to sums of numbers too!

Input & Output

example_1.py โ€” Basic Case
$ Input: [3,6,5,1,8]
โ€บ Output: 18
๐Ÿ’ก Note: We can select elements [3,6,8,1] to get sum = 18, which is divisible by 3. This is the maximum possible.
example_2.py โ€” All Divisible
$ Input: [4]
โ€บ Output: 0
๐Ÿ’ก Note: Since 4 % 3 = 1, we cannot form any sum divisible by 3 using this element, so we return 0.
example_3.py โ€” Multiple Options
$ Input: [1,2,3,4,4]
โ€บ Output: 12
๐Ÿ’ก Note: We can select [3,4,4,1] to get sum = 12, which is divisible by 3. Other combinations like [3] give smaller sums.

Constraints

  • 1 โ‰ค nums.length โ‰ค 4 ร— 104
  • 0 โ‰ค nums[i] โ‰ค 104
  • The array can contain zeros
  • At minimum, we can always return 0 (empty subset)

Visualization

Tap to expand
The Remainder Bucket StrategyBucket 0รท3 remainder 015Bucket 1รท3 remainder 110Bucket 2รท3 remainder 214Processing [3, 6, 5, 1]:Step 1: Add 3 โ†’ (0+3)%3=0 โ†’ Bucket 0 = max(0, 3) = 3Step 2: Add 6 โ†’ (3+6)%3=0 โ†’ Bucket 0 = max(3, 9) = 9Step 3: Add 5 โ†’ (9+5)%3=2 โ†’ Bucket 2 = max(-โˆž, 14) = 14Step 4: Add 1 โ†’ (14+1)%3=0 โ†’ Bucket 0 = max(9, 15) = 15Result: Maximum sum divisible by 3 = 15๐ŸŽฏ Key Insight: Track maximum sums by remainderOnly remainder 0 gives us sums divisible by 3!
Understanding the Visualization
1
Initialize Buckets
Bucket 0 starts with 0 (empty sum), others start empty
2
Process Numbers
For each number, see which bucket it would land in when added to existing sums
3
Update Buckets
Update each bucket with the maximum possible sum for that remainder
4
Get Result
The answer is the value in bucket 0
Key Takeaway
๐ŸŽฏ Key Insight: By tracking the maximum sum for each remainder (0, 1, 2), we can efficiently build the optimal solution without generating all possible subsets.
Asked in
Google 42 Amazon 35 Meta 28 Microsoft 22
42.4K Views
Medium-High Frequency
~18 min Avg. Time
1.8K 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