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 Three INPUT nums = [3, 6, 5, 1, 8] 3 6 5 1 8 idx 0 idx 1 idx 2 idx 3 idx 4 Classify by mod 3: mod 0: 3, 6 (sum=9) mod 1: 1 (sum=1) mod 2: 5, 8 (sum=13) Total sum = 23 23 mod 3 = 2 (Need adjustment!) ALGORITHM STEPS 1 Calculate Total Sum Sum all: 3+6+5+1+8 = 23 2 Check Remainder 23 mod 3 = 2 Not divisible! Need fix. 3 Greedy Choice Remainder = 2, so either: - Remove smallest mod 2 - Remove two smallest mod 1 Option A: Remove 5 (mod 2) 23 - 5 = 18 Option B: Remove two mod 1 nums Only have 1, not optimal 4 Select Best Option Remove 5: gives max sum 18 18 mod 3 = 0 [OK] FINAL RESULT Selected Elements: 3 6 1 8 Excluded: 5 Sum = 3 + 6 + 1 + 8 18 Maximum Sum 18 / 3 = 6 [OK] Divisible by 3! Key Insight: The greedy approach groups numbers by their remainder when divided by 3 (mod 0, 1, or 2). If total sum mod 3 = 1: remove smallest mod 1 number OR two smallest mod 2 numbers. If total sum mod 3 = 2: remove smallest mod 2 number OR two smallest mod 1 numbers. TutorialsPoint - Greatest Sum Divisible by Three | Greedy Approach
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