Since the answer may not fit in an integer data type, return the answer as a string.
If there is no answer return an empty string.
Input: digits = [8,1,9]
Output: "981"
Input: digits = [8,6,7,1,0]
Output: "8760"
Input: digits = [1]
Output: ""
Input: digits = [0,0,0,0,0,0]
Output: "0"
给一个数,能去掉一部分数字并重新组合成为3的倍数,最大能组成的数可能是多少。这里要利用到一个性质,三的倍数满足每个位上的数字相加也是三的倍数,同时当余数不为0时,去掉会导致余数为1或2的数也就能生成3的倍数。分为两种情况,单个数导致的余数为1或2,和两个数相加除3导致的余数为1或2。不用考虑三个数的情况,因为(不考虑0)三个数和一定大于等于3,以被前面两种情况包括。因此在从大到小排序后满足数尽量大后,对以上Ⅴ种情况分类讨论。
class Solution {
public:
string largestMultipleOfThree(vector<int>& digits) {
sort(digits.begin(), digits.end(), greater<int>());
int sum = accumulate(digits.begin(), digits.end(), 0);
if (sum == 0) return "0";
const int N = digits.size();
const auto print = [&]() {
if (digits[0] == '0') return to_string(0);
stringstream ss;
for (const auto d : digits) {
if (d == -1) continue;
ss << d;
}
return ss.str();
};
if (sum % 3 == 0) return print();
if (sum % 3 == 1) {
for (int i = N - 1; i >= 0; --i) {
if (digits[i] == 1 or digits[i] == 4 or digits[i] == 7) {
digits[i] = -1;
return print();
}
}
for (int i = N - 1, cnt = 0; i >= 0; --i) {
if (digits[i] == 2 or digits[i] == 5 or digits[i] == 8) {
digits[i] = -1;
if (cnt == 1) {
return print();
}
++cnt;
}
}
}
if (sum % 3 == 2) {
for (int i = N - 1; i >= 0; --i) {
if (digits[i] == 2 or digits[i] == 5 or digits[i] == 8) {
digits[i] = -1;
return print();
}
}
for (int i = N - 1, cnt = 0; i >= 0; --i) {
if (digits[i] == 1 or digits[i] == 4 or digits[i] == 7) {
digits[i] = -1;
if (cnt == 1) {
return print();
}
++cnt;
}
}
}
return "";
}
};