<p>Given an array of digits <code>digits</code>, return <em>the largest multiple of <strong>three</strong> that can be formed by concatenating some of the given digits in <strong>any order</strong></em>. If there is no answer return an empty string.</p>

<p>Since the answer may not fit in an integer data type, return the answer as a string. Note that the returning answer must not contain unnecessary leading zeros.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> digits = [8,1,9]
<strong>Output:</strong> &quot;981&quot;
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> digits = [8,6,7,1,0]
<strong>Output:</strong> &quot;8760&quot;
</pre>

<p><strong class="example">Example 3:</strong></p>

<pre>
<strong>Input:</strong> digits = [1]
<strong>Output:</strong> &quot;&quot;
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= digits.length &lt;= 10<sup>4</sup></code></li>
	<li><code>0 &lt;= digits[i] &lt;= 9</code></li>
</ul>

class Solution:
    def largestMultipleOfThree(self, digits: List[int]) -> str:
        digits.sort(key = lambda x: -x)
        n = len(digits)
        dp = [ ["" for _ in range(3)] for _ in range(n)]
        # dp[i][r] represents the largest number s formed by some of given digits[0:i+1] such that s % 3 = r.

        r = digits[0] % 3
        dp[0][r] = str(digits[0])
        
        for i in range(1,n):
            for r in range(3):                
                # case 1: Add digits[i] to the tail of dp[i-1][j], where (j+digits[i]) % 3 = r and 0<=j<3.
                # Note that j+digits[i] = 3k+r. Thus, j = r-digits[i]+3k and j = (r-digits[i])%3. Therefore,j=(r-digits[i]+3)%3.
            
                di = dp[i-1][(r-digits[i]+3) % 3]
                if di != "": 
                    if di == "0": # leading zero
                        di = str(digits[i]) # ignore the leading zero
                    else:
                        di += str(digits[i]) # add digits[i] to the tail of dp[i-1][j]

                elif (digits[i] % 3) == r: # if di == "" and digits[i] % 3 == r, then digits[i] is the only digit that meets the condition
                    di = str(digits[i])
                # else: di == ""

                #-- case 2: Do not add digits[i] to the tail of dp[i-1][r]
                dix = dp[i-1][r]

                #-- compute max(di,dix)
                if len(di) > len(dix):
                    dp[i][r] = di
                elif len(di) < len(dix):
                    dp[i][r] = dix
                else: # len(di) == len(dix)
                    dp[i][r] = dix # Note that the list of digits is in non-increasing order. Thus, the tail digit of "di", digits[i], is less than or equal to any digit in "dix", which is selected from digits[0] to digits[i-1].

        return dp[n-1][0]

343