-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathmaximum-sum-of-three-numbers-divisible-by-three.py
More file actions
49 lines (45 loc) · 1.27 KB
/
maximum-sum-of-three-numbers-divisible-by-three.py
File metadata and controls
49 lines (45 loc) · 1.27 KB
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# Time: O(n)
# Space: O(1)
# sort, math
class Solution(object):
def maximumSum(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
def add(arr, x):
for i in xrange(len(arr)):
if x > arr[i]:
arr[i], x = x, arr[i]
if len(arr) != 3:
arr.append(x)
group = [[] for _ in xrange(3)]
for x in nums:
add(group[x%3], x)
result = 0
for g in group:
if len(g) == 3:
result = max(result, sum(g))
if group[0] and group[1] and group[2]:
result = max(result, group[0][0]+group[1][0]+group[2][0])
return result
# Time: O(nlogn)
# Space: O(n)
# sort, math
class Solution2(object):
def maximumSum(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
group = [[] for _ in xrange(3)]
for x in nums:
group[x%3].append(x)
result = 0
for g in group:
g.sort(reverse=True)
if len(g) >= 3:
result = max(result, sum(g[i] for i in xrange(3)))
if group[0] and group[1] and group[2]:
result = max(result, group[0][0]+group[1][0]+group[2][0])
return result