AlgoInsight

DSA problem

Greatest Sum Divisible by Three

Medium1-D DPPattern: 1-D DPtop600GoogleAmazonMicrosoftAppleBloomberg

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

This is an elegant 1-D DP with a tiny state space. The key insight is that the only information we need about a "running sum so far" is its value modulo 3 — there are exactly three possible residues, so we can track the best achievable sum for each residue.

Define dp[r] to be the maximum sum we can build whose value is congruent to r (mod 3). Initially dp[0] = 0 (empty sum) and dp[1] = dp[2] = -infinity (no element seen yet that gives those residues).

For each n in nums, every existing residue class r can be extended by including n, producing a new sum with residue (r + n) % 3. The update is therefore: new_dp[(r + n) % 3] = max(dp[(r + n) % 3], dp[r] + n) for all r. To avoid using the just-updated values inside the same iteration, snapshot dp into a local copy before applying the three updates.

After processing the entire array, dp[0] is the answer: the largest sum whose value mod 3 is zero. The whole algorithm is O(n) time and O(1) space.

Examples

Example 1
Input: nums = [3,6,5,1,8]
Output: 18
Explanation: Pick 3, 6, 1, 8 (sum = 18). That sum is divisible by 3.
Example 2
Input: nums = [4]
Output: 0
Explanation: No nonempty subset has sum divisible by 3, so return the empty sum 0.
Example 3
Input: nums = [1,2,3,4,4]
Output: 12
Explanation: Pick 1, 3, 4, 4 (sum = 12). That sum is divisible by 3.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

dp1d-dparraymathgreedy

Browse all DSA problems