Largest Multiple of Three LeetCode solution in Python

1
class Solution:
2
def largestMultipleOfThree(self, digits: List[int]) -> str:
3
A = digits
4
A.sort()
5
A.reverse()
6

7
@cache
8
def DP(
9
i, r
10
): # max number whose remainder is r using subarray [0:i] (inclusive)
11
if i == 0:
12
if A[0] % 3 == r:
13
return A[0]
14
else:
15
return 0
16

17
Ra = DP(i - 1, r)
18
Rb = [
19
x for j in range(3) for x in (DP(i - 1, j) * 10 + A[i],) if x % 3 == r
20
]
21

22
return max([Ra, *Rb])
23

24
ans = DP(len(A) - 1, 0)
25

26
if ans == 0 and 0 not in A:
27
return ""
28
else:
29
return str(ans)

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0