3780. Maximum Sum of Three Numbers Divisible by Three
Description
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 of4 + 2 + 3 = 9.(2, 3, 1)with a sum of2 + 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] <= 105
Solutions
Solution 1: Sorting + Grouping + Enumeration
Thinking
Three numbers sum to a multiple of \(3\) iff their residues are \((0,0,0)\), \((1,1,1)\), \((2,2,2)\), or \((0,1,2)\). After grouping by residue and sorting each group descending, we try pairs of groups and take the best available value from the third.
We first sort the array \(\textit{nums}\), then divide the elements in the array into three groups based on their modulo \(3\) results, denoted as \(\textit{g}[0]\), \(\textit{g}[1]\), and \(\textit{g}[2]\). Where \(\textit{g}[i]\) stores all elements that satisfy \(\textit{nums}[j] \bmod 3 = i\).
Next, we enumerate the cases of selecting one element each from \(\textit{g}[a]\) and \(\textit{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 \(\textit{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 \(\textit{g}[a]\) and \(\textit{g}[b]\), then take out the largest element from \(\textit{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 \(\textit{nums}\). The space complexity is \(O(n)\).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | |