File tree Expand file tree Collapse file tree 1 file changed +33
-0
lines changed
1262-greatest-sum-divisible-by-three Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Original file line number Diff line number Diff line change 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 ))
You can’t perform that action at this time.
0 commit comments