Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
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 <= 1051 <= nums[i] <= 105Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Greedy
[4,2,3,1]
[2,1,5]
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #3780: Maximum Sum of Three Numbers Divisible by Three
class Solution {
public int maximumSum(int[] nums) {
Arrays.sort(nums);
List<Integer>[] g = new ArrayList[3];
Arrays.setAll(g, k -> new ArrayList<>());
for (int x : nums) {
g[x % 3].add(x);
}
int ans = 0;
for (int a = 0; a < 3; a++) {
if (!g[a].isEmpty()) {
int x = g[a].remove(g[a].size() - 1);
for (int b = 0; b < 3; b++) {
if (!g[b].isEmpty()) {
int y = g[b].remove(g[b].size() - 1);
int c = (3 - (a + b) % 3) % 3;
if (!g[c].isEmpty()) {
int z = g[c].get(g[c].size() - 1);
ans = Math.max(ans, x + y + z);
}
g[b].add(y);
}
}
g[a].add(x);
}
}
return ans;
}
}
// Accepted solution for LeetCode #3780: Maximum Sum of Three Numbers Divisible by Three
func maximumSum(nums []int) int {
sort.Ints(nums)
g := make([][]int, 3)
for _, x := range nums {
g[x%3] = append(g[x%3], x)
}
ans := 0
for a := 0; a < 3; a++ {
if len(g[a]) > 0 {
x := g[a][len(g[a])-1]
g[a] = g[a][:len(g[a])-1]
for b := 0; b < 3; b++ {
if len(g[b]) > 0 {
y := g[b][len(g[b])-1]
g[b] = g[b][:len(g[b])-1]
c := (3 - (a+b)%3) % 3
if len(g[c]) > 0 {
z := g[c][len(g[c])-1]
ans = max(ans, x+y+z)
}
g[b] = append(g[b], y)
}
}
g[a] = append(g[a], x)
}
}
return ans
}
# Accepted solution for LeetCode #3780: Maximum Sum of Three Numbers Divisible by Three
class Solution:
def maximumSum(self, nums: List[int]) -> int:
nums.sort()
g = [[] for _ in range(3)]
for x in nums:
g[x % 3].append(x)
ans = 0
for a in range(3):
if g[a]:
x = g[a].pop()
for b in range(3):
if g[b]:
y = g[b].pop()
c = (3 - (a + b) % 3) % 3
if g[c]:
z = g[c][-1]
ans = max(ans, x + y + z)
g[b].append(y)
g[a].append(x)
return ans
// Accepted solution for LeetCode #3780: Maximum Sum of Three Numbers Divisible by Three
// Rust example auto-generated from java reference.
// Replace the signature and local types with the exact LeetCode harness for this problem.
impl Solution {
pub fn rust_example() {
// Port the logic from the reference block below.
}
}
// Reference (java):
// // Accepted solution for LeetCode #3780: Maximum Sum of Three Numbers Divisible by Three
// class Solution {
// public int maximumSum(int[] nums) {
// Arrays.sort(nums);
// List<Integer>[] g = new ArrayList[3];
// Arrays.setAll(g, k -> new ArrayList<>());
// for (int x : nums) {
// g[x % 3].add(x);
// }
// int ans = 0;
// for (int a = 0; a < 3; a++) {
// if (!g[a].isEmpty()) {
// int x = g[a].remove(g[a].size() - 1);
// for (int b = 0; b < 3; b++) {
// if (!g[b].isEmpty()) {
// int y = g[b].remove(g[b].size() - 1);
// int c = (3 - (a + b) % 3) % 3;
// if (!g[c].isEmpty()) {
// int z = g[c].get(g[c].size() - 1);
// ans = Math.max(ans, x + y + z);
// }
// g[b].add(y);
// }
// }
// g[a].add(x);
// }
// }
// return ans;
// }
// }
// Accepted solution for LeetCode #3780: Maximum Sum of Three Numbers Divisible by Three
function maximumSum(nums: number[]): number {
nums.sort((a, b) => a - b);
const g: number[][] = Array.from({ length: 3 }, () => []);
for (const x of nums) {
g[x % 3].push(x);
}
let ans = 0;
for (let a = 0; a < 3; a++) {
if (g[a].length > 0) {
const x = g[a].pop()!;
for (let b = 0; b < 3; b++) {
if (g[b].length > 0) {
const y = g[b].pop()!;
const c = (3 - ((a + b) % 3)) % 3;
if (g[c].length > 0) {
const z = g[c][g[c].length - 1];
ans = Math.max(ans, x + y + z);
}
g[b].push(y);
}
}
g[a].push(x);
}
}
return ans;
}
Use this to step through a reusable interview workflow for this problem.
Try every possible combination of choices. With n items each having two states (include/exclude), the search space is 2ⁿ. Evaluating each combination takes O(n), giving O(n × 2ⁿ). The recursion stack or subset storage uses O(n) space.
Greedy algorithms typically sort the input (O(n log n)) then make a single pass (O(n)). The sort dominates. If the input is already sorted or the greedy choice can be computed without sorting, time drops to O(n). Proving greedy correctness (exchange argument) is harder than the implementation.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Locally optimal choices may fail globally.
Usually fails on: Counterexamples appear on crafted input orderings.
Fix: Verify with exchange argument or monotonic objective before committing.