<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 {
public:
    void answer(vector<int>& ans, int n, vector<int> vtr) {
        for (int i = 0; i < n; i++) {
            ans.push_back(vtr[i]);
        }
        return;
    }

    string largestMultipleOfThree(vector<int>& digits) {
        int n = digits.size();
        vector<vector<int>> vtr(3);
        for (auto i : digits)
            vtr[i % 3].push_back(i);

        vector<int> ans;
        answer(ans, vtr[0].size(), vtr[0]);

        sort(vtr[1].begin(), vtr[1].end());
        sort(vtr[2].begin(), vtr[2].end());
        reverse(vtr[1].begin(), vtr[1].end());
        reverse(vtr[2].begin(), vtr[2].end());

        int x = vtr[1].size() % 3, y = vtr[2].size() % 3;
        if (x == y) {
            answer(ans, vtr[1].size(), vtr[1]);
            answer(ans, vtr[2].size(), vtr[2]);
        } else if (abs(y - x) == 1) {
            int val = 0;
            x + y == 3 ? val = 1 : val = 0;
            answer(ans, vtr[1].size() - (x - val), vtr[1]);
            answer(ans, vtr[2].size() - (y - val), vtr[2]);
        } else {
            if (vtr[1].size() == 0 || vtr[2].size() == 0) {
                answer(ans, vtr[1].size() - x, vtr[1]);
                answer(ans, vtr[2].size() - y, vtr[2]);
            } else {
                answer(ans, vtr[1].size() - (x + 1) % 3, vtr[1]);
                answer(ans, vtr[2].size() - (y + 1) % 3, vtr[2]);
            }
        }

        string str = "";
        sort(ans.begin(), ans.end());
        reverse(ans.begin(), ans.end());
        for (auto i : ans) {
            str.push_back('0' + i);
        }
        return str[0] == '0' ? "0" : str;
    }
};
28180