problemmediumalgorithmsleetcode-1262leetcode 1262leetcode1262

Greatest Sum Divisible by Three

MediumUpdated: Aug 2, 2025
Practice on:

Problem

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

Examples

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^4
  • 1 <= nums[i] <= 10^4

Solution

Method 1 – Dynamic Programming with Remainder States

Intuition

To maximize the sum divisible by 3, we can use dynamic programming to track the best possible sum for each remainder (0, 1, 2) as we iterate through the array. For each number, we update the possible sums for each remainder by adding the number and taking modulo 3.

Approach

  1. Initialize a DP array of size 3, where dp[r] is the maximum sum with remainder r.
  2. For each number in nums, for each remainder, update the DP array with the new possible sums.
  3. After processing all numbers, dp[0] will be the answer (maximum sum divisible by 3).

Code

C++
class Solution {
public:
    int maxSumDivThree(vector<int>& nums) {
        vector<int> dp(3, 0);
        for (int x : nums) {
            vector<int> ndp = dp;
            for (int r = 0; r < 3; ++r) {
                int nr = (r + x) % 3;
                ndp[nr] = max(ndp[nr], dp[r] + x);
            }
            dp = ndp;
        }
        return dp[0];
    }
};
Go
func maxSumDivThree(nums []int) int {
    dp := [3]int{}
    for _, x := range nums {
        ndp := dp
        for r := 0; r < 3; r++ {
            nr := (r + x) % 3
            if ndp[nr] < dp[r]+x {
                ndp[nr] = dp[r]+x
            }
        }
        dp = ndp
    }
    return dp[0]
}
Java
class Solution {
    public int maxSumDivThree(int[] nums) {
        int[] dp = new int[3];
        for (int x : nums) {
            int[] ndp = dp.clone();
            for (int r = 0; r < 3; r++) {
                int nr = (r + x) % 3;
                ndp[nr] = Math.max(ndp[nr], dp[r] + x);
            }
            dp = ndp;
        }
        return dp[0];
    }
}
Kotlin
class Solution {
    fun maxSumDivThree(nums: IntArray): Int {
        var dp = IntArray(3)
        for (x in nums) {
            val ndp = dp.copyOf()
            for (r in 0..2) {
                val nr = (r + x) % 3
                ndp[nr] = maxOf(ndp[nr], dp[r] + x)
            }
            dp = ndp
        }
        return dp[0]
    }
}
Python
def maxSumDivThree(nums: list[int]) -> int:
    dp = [0, 0, 0]
    for x in nums:
        ndp = dp[:]
        for r in range(3):
            nr = (r + x) % 3
            ndp[nr] = max(ndp[nr], dp[r] + x)
        dp = ndp
    return dp[0]
Rust
impl Solution {
    pub fn max_sum_div_three(nums: Vec<i32>) -> i32 {
        let mut dp = [0; 3];
        for &x in &nums {
            let ndp = dp;
            for r in 0..3 {
                let nr = (r + x % 3) % 3;
                dp[nr] = dp[nr].max(ndp[r] + x);
            }
        }
        dp[0]
    }
}
TypeScript
class Solution {
    maxSumDivThree(nums: number[]): number {
        let dp = [0, 0, 0];
        for (const x of nums) {
            const ndp = [...dp];
            for (let r = 0; r < 3; r++) {
                const nr = (r + x) % 3;
                ndp[nr] = Math.max(ndp[nr], dp[r] + x);
            }
            dp = ndp;
        }
        return dp[0];
    }
}

Complexity

  • ⏰ Time complexity: O(n), since we process each number and update a constant-size DP array.
  • 🧺 Space complexity: O(1), only a constant number of variables are used.

Comments