Approach
Sorting and greedy selection
For Maximum Sum of Three Numbers Divisible by Three, the implementation first exposes a useful order, then scans that order while making locally justified choices.
- Choose the key that reveals the greedy or grouping structure.
- Sort the relevant records by that key.
- Scan in order, maintaining the invariant that makes each local choice safe.
Code notes
- 50 lines of Python from the credited upstream file maximum-sum-of-three-numbers-divisible-by-three.py.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected.
Complexity
Sorting is typically the dominant term unless the subsequent scan uses a more expensive nested operation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 45class Solution(object):6 def maximumSum(self, nums):7 """8 :type nums: List[int]9 :rtype: int10 """11 def add(arr, x):12 for i in xrange(len(arr)):13 if x > arr[i]:14 arr[i], x = x, arr[i]15 if len(arr) != 3:16 arr.append(x)17 18 group = [[] for _ in xrange(3)]19 for x in nums:20 add(group[x%3], x)21 result = 022 for g in group:23 if len(g) == 3:24 result = max(result, sum(g))25 if group[0] and group[1] and group[2]:26 result = max(result, group[0][0]+group[1][0]+group[2][0])27 return result28 29 30313233class Solution2(object):34 def maximumSum(self, nums):35 """36 :type nums: List[int]37 :rtype: int38 """39 group = [[] for _ in xrange(3)]40 for x in nums:41 group[x%3].append(x)42 result = 043 for g in group:44 g.sort(reverse=True)45 if len(g) >= 3:46 result = max(result, sum(g[i] for i in xrange(3)))47 if group[0] and group[1] and group[2]:48 result = max(result, group[0][0]+group[1][0]+group[2][0])49 return result50