Greatest Sum Divisible by Three LeetCode solution in Python

1
from math import inf
2

3

4
class Solution:
5
def maxSumDivThree(self, nums: List[int]) -> int:
6
res = 0
7
r1_min1 = inf
8
r1_min2 = inf
9
r2_min1 = inf
10
r2_min2 = inf
11

12
for v in nums:
13
res += v
14
if v % 3 == 1:
15
if v < r1_min1:
16
r1_min2 = r1_min1
17
r1_min1 = v
18
elif v < r1_min2:
19
r1_min2 = v
20
elif v % 3 == 2:
21
if v < r2_min1:
22
r2_min2 = r2_min1
23
r2_min1 = v
24
elif v < r2_min2:
25
r2_min2 = v
26

27
if res % 3 == 1:
28
res -= min(r1_min1, r2_min1 + r2_min2)
29
elif res % 3 == 2:
30
res -= min(r2_min1, r1_min1 + r1_min2)
31

32
return res

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0