Skip to content

Commit 989fcad

Browse files
committed
Create 1361.形成三的最大倍数.js
1 parent 9552019 commit 989fcad

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

1361.形成三的最大倍数.js

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/**
2+
* @param {number[]} digits
3+
* @return {string}
4+
*/
5+
var largestMultipleOfThree = function(digits) {
6+
digits.sort((a, b) => a - b);
7+
const map = [[], [], []];
8+
9+
let sum = 0;
10+
for (const n of digits) {
11+
map[n % 3].push(n);
12+
sum += n;
13+
}
14+
15+
function formatResult() {
16+
const arr = [...map[0], ...map[1], ...map[2]].sort((a, b) => b - a);
17+
while (arr.length > 1 && arr[0] === 0) {
18+
arr.shift();
19+
}
20+
return arr.join('');
21+
}
22+
23+
if (sum % 3 === 0) {
24+
return formatResult();
25+
} else {
26+
const a = sum % 3;
27+
const b = a === 1 ? 2 : 1;
28+
if (map[a].length >= 1) {
29+
map[a].shift();
30+
} else if (map[b].length >= 2) {
31+
map[b].shift();
32+
map[b].shift();
33+
} else {
34+
return '';
35+
}
36+
return formatResult();
37+
}
38+
};

0 commit comments

Comments
 (0)