Skip to content

Commit e4ef779

Browse files
committed
Time: 23 ms (73.31%), Space: 22 MB (36.95%) - LeetHub
1 parent f6108ca commit e4ef779

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
# time complexity: O(nlogn)
2+
# space complexity: O(n)
3+
from typing import List
4+
5+
6+
class Solution:
7+
def maxSumDivThree(self, nums: List[int]) -> int:
8+
A = sorted([x for x in nums if x % 3 == 1], reverse=True)
9+
B = sorted([x for x in nums if x % 3 == 2], reverse=True)
10+
total, remove = sum(nums), float("inf")
11+
12+
if total % 3 == 0:
13+
remove = 0
14+
elif total % 3 == 1:
15+
if len(A) >= 1:
16+
remove = min(remove, A[-1])
17+
if len(B) >= 2:
18+
remove = min(remove, B[-2] + B[-1])
19+
else:
20+
if len(A) >= 2:
21+
remove = min(remove, A[-2] + A[-1])
22+
if len(B) >= 1:
23+
remove = min(remove, B[-1])
24+
25+
return total - remove
26+
27+
28+
nums = [3, 6, 5, 1, 8]
29+
print(Solution().maxSumDivThree(nums))
30+
nums = [4]
31+
print(Solution().maxSumDivThree(nums))
32+
nums = [1, 2, 3, 4, 4]
33+
print(Solution().maxSumDivThree(nums))

0 commit comments

Comments
 (0)