Greatest Sum Divisible by Three Problem
Description
LeetCode Problem 1262.
Given an integer array nums, return the maximum possible sum of elements of the array such that it is divisible by three.
Example 1:
Input: nums = [3,6,5,1,8]
Output: 18
Explanation: Pick numbers 3, 6, 1 and 8 their sum is 18 (maximum sum divisible by 3).
Example 2:
Input: nums = [4]
Output: 0
Explanation: Since 4 is not divisible by 3, do not pick any number.
Example 3:
Input: nums = [1,2,3,4,4]
Output: 12
Explanation: Pick numbers 1, 3, 4 and 4 their sum is 12 (maximum sum divisible by 3).
Constraints:
1 <= nums.length <= 4 * 10^41 <= nums[i] <= 10^4
Solution
Approach: Dynamic Programming on the Remainder
When we choose a subset, all that matters about the sum for the future is its remainder modulo 3. So for the numbers seen so far we keep three values: best[r], the largest sum of a subset whose sum leaves remainder r (or -1 if no subset has that remainder yet). At the start only the empty subset exists, so best = [0, -1, -1].
For each number x, every subset either skips x or takes it:
- Skip: every
best[r]stays as it is. - Take: a subset with remainder
rbecomes one with remainder(r + x) mod 3and sumbest[r] + x.
We compute the new values from a copy of the old ones, so x is never added twice in the same step. The answer is best[0], which is at least 0 thanks to the empty subset. This matters for Example 2 ([4]), where no non-empty subset works.
In Example 1, the total 23 leaves remainder 2, and the DP finds 18, which leaves out 5, the smallest number with remainder 2.
Complexity: O(n) time and O(1) extra space.
class Solution:
def maxSumDivThree(self, nums: List[int]) -> int:
# best[r]: the largest sum of a subset so far with sum % 3 == r, or -1 if there is none yet.
best = [0, -1, -1]
for x in nums:
nxt = best[:] # not taking x keeps every state
for r in range(3):
if best[r] >= 0:
t = (r + x) % 3
nxt[t] = max(nxt[t], best[r] + x)
best = nxt
return best[0]