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
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.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code