Greatest Sum Divisible by Three โ A Deep Dive with Greedy and DP Solutions
Problem Description
The Greatest Sum Divisible by Three problem asks: given an array nums of non-negative integers, find the maximum possible sum of its elements that is divisible by 3. If no combination of elements can sum to a multiple of 3, the result should be 0. For example, with nums = [3,6,5,1,8], the highest sum divisible by 3 is 18 (by picking 3, 6, 1, and 8). This problem is a subset-sum optimization with a divisibility constraint, and it commonly appears in coding interviews due to the need for clever reasoning about remainders and dynamic programming.
Both implementations below assume non-negative inputs and a total strictly below the platform's maximum int. Negative inputs need a different formulation; arbitrary large sums need checked arithmetic or a wider representation. The sentinel is never added to a valid sum in the greedy implementation, and the DP explicitly ignores unreachable states.
Intuitive Greedy Solution (Sorting & Remainders)
A straightforward approach is to use a greedy strategy based on the total sum's remainder when divided by 3. The idea is to include as many numbers as possible (to maximize sum), then remove the smallest necessary elements to fix the sum's remainder so that it becomes divisible by 3:
Calculate Total Sum and Remainder: Compute the sum of all numbers and determine r = sum % 3. If r == 0, then the total sum is already divisible by 3, and that's our answer.
Handle Remainder 1: If r == 1, we need to drop a small portion of the sum that leaves a remainder of 1. We have two ways:
- Remove the smallest single element whose value mod 3 is 1.
- Or remove the two smallest elements whose values mod 3 are 2 (because 2 + 2 โก 1 mod 3).
We choose the option that removes the smallest total amount (to keep the sum as large as possible).
Handle Remainder 2: If r == 2, adjust symmetrically:
- Remove the smallest single element with value mod 3 equal to 2.
- Or remove the two smallest elements with values mod 3 equal to 1 (since 1 + 1 โก 2 mod 3).
Again, choose the minimal removal sum.
Edge Case: If no suitable element combination exists to fix the remainder (when neither removal candidate is present), the result falls back to 0.
This greedy method works because removing the smallest-possible values to correct the remainder ensures we lose the least amount from the total sum, thus keeping it maximal. By categorizing numbers by their remainder classes (0, 1, or 2 modulo 3) and sorting or scanning for the smallest in each category, we can implement this efficiently.
Go Implementation โ Greedy Approach:
func maxSumDivisibleBy3Greedy(nums []int) int {
// Calculate total sum and track smallest elements for mod 1 and mod 2
sum := 0
const inf = int(^uint(0) >> 1) // sentinel; valid totals must be smaller
rem1Min1, rem1Min2 := inf, inf // smallest and second-smallest for remainder 1
rem2Min1, rem2Min2 := inf, inf // smallest and second-smallest for remainder 2
for _, num := range nums {
sum += num
switch num % 3 {
case 1:
// update two smallest for remainder 1
if num < rem1Min1 {
rem1Min2 = rem1Min1
rem1Min1 = num
} else if num < rem1Min2 {
rem1Min2 = num
}
case 2:
// update two smallest for remainder 2
if num < rem2Min1 {
rem2Min2 = rem2Min1
rem2Min1 = num
} else if num < rem2Min2 {
rem2Min2 = num
}
}
}
if sum % 3 == 0 {
return sum
} else if sum % 3 == 1 {
// Option 1: remove one smallest mod-1 element
removeOne := inf
if rem1Min1 != inf {
removeOne = rem1Min1
}
// Option 2: remove two smallest mod-2 elements
removeTwo := inf
if rem2Min2 != inf {
removeTwo = rem2Min1 + rem2Min2
}
// Remove the minimal total to fix remainder
toRemove := removeOne
if removeTwo < toRemove {
toRemove = removeTwo
}
if toRemove == inf {
return 0 // no valid combination to fix remainder
}
return sum - toRemove
} else { // sum % 3 == 2
removeOne := inf
if rem2Min1 != inf {
removeOne = rem2Min1
}
removeTwo := inf
if rem1Min2 != inf {
removeTwo = rem1Min1 + rem1Min2
}
toRemove := removeOne
if removeTwo < toRemove {
toRemove = removeTwo
}
if toRemove == inf {
return 0
}
return sum - toRemove
}
}
How it works: The code accumulates the total sum and records the smallest one or two elements in each remainder category (1 and 2). Depending on the total sum's remainder, it then subtracts the minimal required value(s) to make the sum divisible by 3. For instance, in the earlier example [3,6,5,1,8] (total sum 23, remainder 2), rem2Min1 would be 5 and thus the result becomes 23 - 5 = 18. If the array were [4] (sum 4, remainder 1), rem1Min1 is 4 and removing it yields 0, which is the correct result.
Complexity: This greedy approach runs in linear time O(n) for scanning the array (or O(n log n) if we explicitly sorted the array, which isn't necessary here). The space overhead is O(1), using only a few counters for tracking minima.
Optimized Remainder-Tracking Solution (Dynamic Programming)
While the greedy method is intuitive, a more algorithmically rigorous solution uses dynamic programming (DP) to track achievable sums for each remainder class. The key insight is that as we consider each number in the array, it can either join the subset or not, and its inclusion will affect the sum's remainder. We can maintain three running values corresponding to the maximum sum achievable for each remainder (0, 1, 2) modulo 3. This DP approach is linear-time and updates the state in one pass through the array.
Idea: Use an array dp[3] where:
- dp[0] is the maximum sum so far that is divisible by 3 (remainder 0).
- dp[1] is the maximum sum so far with remainder 1.
- dp[2] is the maximum sum so far with remainder 2.
Initially, dp[0] = 0 (sum of zero elements gives 0, which is divisible by 3) and dp[1] and dp[2] can be set to a very negative number to indicate those remainders are not yet attainable. Then for each number x in nums, we update the dp array by considering adding x to each of the current sums. We use a temporary copy of the current dp state during updates to avoid using an updated value in the same iteration. In essence, for each new number x and each remainder state r (0,1,2), the number can create a new sum with remainder (r + x % 3) by adding to a previous sum with remainder r. We take the maximum such sum for each remainder category.
Go Implementation โ DP Approach:
func maxSumDivisibleBy3DP(nums []int) int {
// dp[r] = max sum with remainder r
const NEG_INF = -1 // unreachable; valid sums are non-negative
dp := [3]int{0, NEG_INF, NEG_INF}
for _, num := range nums {
// Snapshot of current state to compute next state
current0, current1, current2 := dp[0], dp[1], dp[2]
switch num % 3 {
case 0:
// Adding a 0-mod-3 number keeps remainder the same
if current0 >= 0 && current0 + num > dp[0] {
dp[0] = current0 + num
}
if current1 >= 0 && current1 + num > dp[1] {
dp[1] = current1 + num
}
if current2 >= 0 && current2 + num > dp[2] {
dp[2] = current2 + num
}
case 1:
// If num % 3 == 1, it affects remainders cyclically: 0->1, 1->2, 2->0
new0 := current2 + num // prev remainder 2 + this 1 -> remainder 0
new1 := current0 + num // prev remainder 0 + this 1 -> remainder 1
new2 := current1 + num // prev remainder 1 + this 1 -> remainder 2
if current2 >= 0 && new0 > dp[0] {
dp[0] = new0
}
if current0 >= 0 && new1 > dp[1] {
dp[1] = new1
}
if current1 >= 0 && new2 > dp[2] {
dp[2] = new2
}
case 2:
// If num % 3 == 2, it affects remainders cyclically: 0->2, 1->0, 2->1
new0 := current1 + num // prev remainder 1 + this 2 -> remainder 0
new1 := current2 + num // prev remainder 2 + this 2 -> remainder 1
new2 := current0 + num // prev remainder 0 + this 2 -> remainder 2
if current1 >= 0 && new0 > dp[0] {
dp[0] = new0
}
if current2 >= 0 && new1 > dp[1] {
dp[1] = new1
}
if current0 >= 0 && new2 > dp[2] {
dp[2] = new2
}
}
}
// dp[0] holds the maximum sum divisible by 3
if dp[0] < 0 {
return 0 // no valid subset except empty
}
return dp[0]
}
How it works: This algorithm effectively explores combinations in a single pass. For each number, it tries adding that number to the best sums of each remainder category (as captured in current0, current1, current2). For example, if num % 3 == 1 and we previously had a sum with remainder 2 (stored in current2), adding this number will yield a new sum with remainder 0 โ we update dp[0] if this new sum is larger than the current dp[0]. By the end, dp[0] is the largest sum with remainder 0, i.e. divisible by 3. We always carry forward the maximum sums for each remainder, so all possible subset sums (mod 3) are implicitly considered without brute-forcing subsets.
Correctness intuition: Because 3 is small, we only track 3 states, and each new number either keeps a sum in the same remainder class or moves it to another. This covers all possibilities of including or excluding each number. The use of a temporary copy (current0, current1, current2) ensures we base the new updates on the state before adding the current number (avoiding using a number more than once). By maintaining maximum sums for each remainder category, we ensure that by the end we have the global maximum for the divisible-by-3 category. (If no elements were chosen, dp[0] remains 0 as initialized, which correctly accounts for the possibility of choosing nothing.)
Complexity: This solution runs in O(n) time โ we make a constant amount of updates per element. Space usage is O(1) (just a fixed-size array of length 3 for dp and a few temporary variables). Despite using a DP concept, it's very space-efficient.
Why This Problem is Asked (Interview Relevance)
This problem is a great interview question because it combines greedy reasoning with modular arithmetic and dynamic programming in a manageable way. It tests a candidate's ability to recognize patterns (specifically, that the modulo 3 constraint partitions the problem into three states) and to optimize beyond brute-force:
-
Greedy vs Dynamic Programming: An interviewer might explore if the candidate can come up with the intuitive greedy fix (adjusting the sum by removing small elements) and then push further for a more algorithmic solution. The DP solution demonstrates understanding of state and transition in algorithms, but in a simpler form than a typical subset-sum DP.
-
Edge Case Handling: The requirement to return 0 if no valid subset exists ensures the candidate thinks about cases where the greedy fix might not be possible (and the DP naturally handles this by falling back to 0).
-
Modular Thinking: Many practical systems (e.g., tasks scheduled in cycles of 3, or distributing loads evenly among 3 servers) might require reasoning about remainders. This problem is a simplified model of ensuring a sum conforms to a modular condition, a useful skill in system design and algorithm design.
-
Efficiency Considerations: The optimal solution runs in linear time with constant space, showing that the candidate can achieve high efficiency. In interviews, showing an initial solution and then refining it to optimal complexity is a valuable demonstration of problem-solving.
Senior engineers and recruiters appreciate these aspects because they reflect on a candidate's coding maturity: the ability to reason about correctness (Why does the greedy approach always work? Why does the DP cover all cases?) and to optimize for performance when needed.
Extensions and Generalizations
While the problem specifically targets divisibility by 3, the approach can be generalized. For instance, one could ask: what about the greatest sum divisible by K for some arbitrary K? The dynamic programming approach extends naturally to tracking K remainder states instead of 3. The time complexity would become O(nยทK), and space O(K). For small constants this is still efficient. However, for large K, a different strategy might be needed (or the greedy strategy might get more complex, as it would involve removing elements whose remainders sum up to K).
Another variation is dealing with other constraints, such as forming the largest number (not just sum) divisible by 3 from a collection of digits โ a known greedy application of the same principle. The logic of removing the smallest digits to adjust the remainder is analogous to the greedy solution we discussed.
TL;DR
Greatest Sum Divisible by Three is an illustrative problem that showcases how understanding remainders and dynamic programming leads to clean and efficient solutions. Both approaches โ greedy and DP โ reach the same correct result, and thinking through both is valuable for solidifying one's grasp of algorithmic problem solving in interviews. By practicing problems like this, engineers reinforce skills in modular arithmetic reasoning and state-based DP optimization, which are broadly applicable in coding interviews and beyond.