Largest Multiple of Three LeetCode solution in JavaScript

1
/**
2
* @param {number[]} digits
3
* @return {string}
4
*/
5
var largestMultipleOfThree = function (digits) {
6
// highest digit first
7
digits.sort((l, r) => r - l);
8

9
// what is the remainder of the total sum?
10
const sumRemainder = digits.reduce((a, c) => a + c, 0) % 3;
11

12
if (sumRemainder) {
13
let targetIndex = 0,
14
i = digits.length - 1;
15

16
// try to find what is the smallest number that can be removed
17
for (; i >= 0; i--) {
18
if ((digits[i] - sumRemainder) % 3 === 0) {
19
targetIndex = i;
20
break;
21
}
22
}
23

24
if (i < 0) {
25
// iterated the whole loop, couldn't find a single number to remove
26
// remove everything but multiples of 3
27
digits = digits.filter((v) => v % 3 === 0);
28
} else {
29
digits.splice(targetIndex, 1);
30
}
31
}
32

33
return digits[0] === 0 ? "0" : digits.join("");
34
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0