Maximum Sum of Three Numbers Divisible by Three Problem
Description
LeetCode Problem 3780.
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 <= 10^51 <= nums[i] <= 10^5
Solution
Approach: Sorting + Grouping + Enumeration
Sort nums and split it into three groups by remainder modulo 3. Enumerate the remainders a and b of the first two chosen numbers; the third must have remainder c = (3 - (a + b) % 3) % 3. For each choice, the best numbers are the largest ones of their groups, so take the largest of g[a], then the largest of g[b] (removing the first one so it is not reused), and the largest left in g[c]. Keep the best sum, or 0 if no valid triple exists.
Complexity: time O(n log n), space O(n), where n is the length of nums.
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