Greatest Sum Divisible by Three LeetCode solution in JavaScript

1
var maxSumDivThree = function (nums) {
2
// there are 3 options for how the sum fit's into 3 via mod % 3
3
// track those 3 options via indices in the dp array
4
// dp[0] = %3 === 0
5
// dp[1] = %3 === 1
6
// dp[2] = %3 === 2
7
let dp = new Array(3).fill(0);
8
for (let num of nums) {
9
for (let i of dp.slice(0)) {
10
let sum = i + num;
11
let mod = sum % 3;
12
// on each pass, set the value of dp[mod] to the Math.max val
13
dp[mod] = Math.max(dp[mod], sum);
14
}
15
}
16
return dp[0];
17
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0