The Greatest Sum Divisible by Three interview question asks you to find the maximum possible sum of a subset of an integer array such that the sum is exactly divisible by 3. You can choose any number of elements from the array.
Companies like Goldman Sachs and Amazon use this Dynamic Programming coding problem to test your ability to handle states based on remainders (modulo arithmetic). It's a variation of the Knapsack problem where the "capacity" is defined by the modulo operation. It evaluates whether you can track multiple states simultaneously to build up an optimal solution.
This problem uses 1D Dynamic Programming with Modulo States.
dp of size 3. dp[i] represents the maximum sum achieved so far that yields a remainder of i when divided by 3. Initialize dp = [0, 0, 0].num in the input array.num, calculate what happens when you add it to the existing sums in dp. Create a temporary copy of dp to avoid modifying the array while iterating over it.s in the current dp: new_sum = s + num. Update the corresponding state in the temporary array: temp[new_sum % 3] = max(temp[new_sum % 3], new_sum).dp[0].nums = [3, 6, 5, 1, 8]
dp = [0, 0, 0].dp = [3, 0, 0].dp = [9, 0, 0].5 % 3 = 2. dp = [9, 0, 14] (9+5=14, rem 2).1 % 3 = 1.
9 + 1 = 10 (rem 1).14 + 1 = 15 (rem 0).dp = [15, 10, 14].8 % 3 = 2.
15 + 8 = 23 (rem 2). max(14, 23) = 23.10 + 8 = 18 (rem 0). max(15, 18) = 18.14 + 8 = 22 (rem 1). max(10, 22) = 22.dp = [18, 22, 23].
Result: 18.dp array directly while iterating through its 3 states for a single number. This can cause a number to be added multiple times.Tracking states by modulo (sum % k) is a standard DP pattern. Practice this pattern, as it applies directly to any problem asking for a subset sum divisible by .
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Maximum Length of Pair Chain | Medium | Solve | |
| Non-overlapping Intervals | Medium | Solve | |
| Reducing Dishes | Hard | Solve | |
| Minimize the Maximum Difference of Pairs | Medium | Solve | |
| Minimum Cost for Cutting Cake I | Medium | Solve |