Skip to main content

Maximum Sum of Three Numbers Divisible by Three - Solution & Explanation

MediumArrayGreedySortingHeap (Priority Queue)10 min readAsked at: Amazon
Practice this problem

Problem Statement

You are given an integer array nums.

Your task is to choose exactly three integers from nums such that their sum is divisible by three.

Return the maximum possible sum of such a triplet. If no such triplet exists, return 0.

 

Example 1:

Input: nums = [4,2,3,1]

Output: 9

Explanation:

The valid triplets whose sum is divisible by 3 are:

  • (4, 2, 3) with a sum of 4 + 2 + 3 = 9.
  • (2, 3, 1) with a sum of 2 + 3 + 1 = 6.

Thus, the answer is 9.

Example 2:

Input: nums = [2,1,5]

Output: 0

Explanation:

No triplet forms a sum divisible by 3, so the answer is 0.

 

Constraints:

  • 3 <= nums.length <= 105
  • 1 <= nums[i] <= 105

Approach Overview

Problem Overview: Given an integer array, pick exactly three numbers whose total sum is divisible by 3. Among all valid triplets, return the maximum possible sum. If no such combination exists, return -1 or the defined failure value depending on the implementation.

Approach 1: Brute Force Triplets (O(n^3) time, O(1) space)

The most direct method checks every possible combination of three elements. Use three nested loops and compute nums[i] + nums[j] + nums[k] for all unique triplets. For each sum, verify whether sum % 3 == 0 and track the maximum valid value. This approach guarantees correctness but becomes impractical when n grows because it evaluates O(n^3) combinations. It’s useful only for understanding the problem constraints or validating optimized solutions.

Approach 2: Sorting + Grouping + Enumeration (O(n log n) time, O(n) space)

This is the practical solution used in most implementations. First sort the array in descending order using techniques from sorting. Then group numbers based on their remainder when divided by 3 (num % 3). The key observation: a sum of three numbers is divisible by 3 when their remainders form one of these combinations: (0,0,0), (1,1,1), (2,2,2), or (0,1,2).

After grouping, enumerate valid remainder combinations and compute the best possible sum using the largest elements from each group. Because the array is sorted, you always pull the highest values first. This reduces the search space dramatically while still guaranteeing the optimal result. The technique combines ideas from array manipulation and simple greedy selection.

Approach 3: Priority Queue by Remainder Groups (O(n log n) time, O(n) space)

Instead of sorting the entire array, push numbers into three max-heaps based on their remainder (0, 1, 2). Heaps allow efficient retrieval of the largest elements in each group. Then evaluate the same valid remainder patterns (0+0+0, 1+1+1, 2+2+2, 0+1+2) by popping the top values from the appropriate heaps. This approach uses a heap (priority queue) to avoid full sorting, though the asymptotic complexity remains similar.

Recommended for interviews: The sorting + grouping strategy is usually the expected answer. Interviewers want to see whether you recognize the remainder pattern that determines divisibility by 3. Starting with the brute force solution demonstrates baseline reasoning, but the grouped greedy approach shows stronger algorithmic insight and clean implementation.

Solution

We first sort the array nums, then divide the elements in the array into three groups based on their modulo 3 results, denoted as g[0], g[1], and g[2]. Where g[i] stores all elements that satisfy nums[j] bmod 3 = i.

Next, we enumerate the cases of selecting one element each from g[a] and g[b], where a, b \in {0, 1, 2}. Based on the modulo 3 results of the two selected elements, we can determine which group the third element should be selected from to ensure that the sum of the triplet is divisible by 3. Specifically, the third element should be selected from g[c], where c = (3 - (a + b) bmod 3) bmod 3.

For each combination of (a, b), we try to take out the largest element from both g[a] and g[b], then take out the largest element from g[c], calculate the sum of these three elements, and update the answer.

The time complexity is O(n log n), where n is the length of the array nums. The space complexity is O(n).

Code

Python

Java

C++

Go

TypeScript

Try this approach in the editor β†’

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Brute Force TripletsO(n^3)O(1)Useful for small arrays or verifying correctness of optimized solutions
Sorting + Grouping + EnumerationO(n log n)O(n)Best general solution; simple logic with reliable performance
Remainder Groups with Max HeapO(n log n)O(n)When you want quick access to largest elements without sorting the entire array

Video Solution

LeetCode 3780 πŸ”₯ Max Sum Divisible by 3 | Biweekly Contest 172 | Smart Mod Logic β€’ Study Placement β€’ 459 views views

Watch 6 more video solutions β†’

Frequently Asked Questions

Is Maximum Sum of Three Numbers Divisible by Three easy or hard?
This problem is typically rated Medium because the brute force solution is obvious but inefficient. The challenge is recognizing the modular arithmetic property that determines which remainder combinations produce a sum divisible by three.
Maximum Sum of Three Numbers Divisible by Three Python/Java solution
The standard implementation sorts the array, groups numbers by remainder (num % 3), and evaluates valid combinations such as (0,0,0) or (0,1,2). This logic is straightforward to implement in Python, Java, C++, Go, or TypeScript with O(n log n) time complexity.
How to solve Maximum Sum of Three Numbers Divisible by Three in O(n)?
An O(n) strategy is possible if you only track the top few values in each remainder group instead of sorting the entire array. Maintain the largest candidates for remainder 0, 1, and 2 while scanning the array once. Then evaluate the valid remainder combinations to compute the maximum divisible sum.
What is the best approach for Maximum Sum of Three Numbers Divisible by Three?
The most practical approach is sorting the array and grouping numbers by their remainder modulo 3. Valid combinations are (0,0,0), (1,1,1), (2,2,2), and (0,1,2). After sorting, choose the largest numbers from the required groups to maximize the sum. This solution runs in O(n log n) time and O(n) space.
Is Maximum Sum of Three Numbers Divisible by Three asked at Google/Amazon/Meta?
Problems involving modular arithmetic, greedy selection, and triplet combinations frequently appear in interviews at companies like Amazon, Google, and Meta. Variations often test recognizing remainder patterns and optimizing beyond brute force enumeration.
What data structure is used in Maximum Sum of Three Numbers Divisible by Three?
Common implementations use arrays or lists to group numbers by remainder modulo 3. Some solutions also use a max heap (priority queue) to efficiently retrieve the largest values from each group. Sorting is another common technique to simplify selection.
What is the time complexity of Maximum Sum of Three Numbers Divisible by Three?
The brute force approach checks every triplet and takes O(n^3) time. The optimized solution sorts the array and groups numbers by remainder, giving O(n log n) time due to sorting and O(n) additional space. Heap-based implementations also run in O(n log n).

Ready to solve this problem?

Practice Maximum Sum of Three Numbers Divisible by Three with our built-in code editor and test cases.

Practice on FleetCode