Greatest Sum Divisible by Three - Problem

Given an integer array nums, return the maximum possible sum of elements of the array such that it is divisible by three.

You can select any subset of elements from the array. The sum of the selected elements must be divisible by 3 to be valid.

Note: An empty subset has sum 0, which is divisible by 3.

Input & Output

Example 1 — Basic Case
$ Input: nums = [3,6,5,1,8]
Output: 18
💡 Note: Select [3,6,1,8] with sum=18. Since 18%3=0, this is valid. This is the maximum possible sum divisible by 3.
Example 2 — All Divisible
$ Input: nums = [4]
Output: 0
💡 Note: 4%3=1, so we cannot include 4. The only valid subset is empty set with sum=0.
Example 3 — Multiple Valid Combinations
$ Input: nums = [1,2,3,4,5,6]
Output: 18
💡 Note: Select [3,4,5,6] with sum=18. Alternative: [1,2,3,6] also gives sum=12, but 18 is larger.

Constraints

  • 1 ≤ nums.length ≤ 4 × 104
  • -104 ≤ nums[i] ≤ 104

Visualization

Tap to expand
Greatest Sum Divisible by ThreeInput: [3,6,5,1,8] → Find maximum sum divisible by 336518SelectedSelectedNot SelectedSelectedSelectedSelected elements: 3 + 6 + 1 + 8 = 18Check: 18 ÷ 3 = 6 remainder 0 ✓Maximum Sum Divisible by 318
Understanding the Visualization
1
Input
Array of integers [3,6,5,1,8]
2
Process
Find subset with maximum sum divisible by 3
3
Output
Maximum sum: 18 (from selecting [3,6,1,8])
Key Takeaway
🎯 Key Insight: Use dynamic programming to track the maximum sum achievable for each remainder state (0, 1, 2)
Asked in
Google 12 Amazon 8 Facebook 6
52.0K Views
Medium Frequency
~25 min Avg. Time
1.2K 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