-
Notifications
You must be signed in to change notification settings - Fork 229
/
Copy path1262-greatest-sum-divisible-by-three.js
50 lines (48 loc) · 1.2 KB
/
1262-greatest-sum-divisible-by-three.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/**
* @param {number[]} nums
* @return {number}
*/
const maxSumDivThree = function (nums) {
const n = nums.length
let dp = [0, -Infinity, -Infinity]
for (let i = n - 1; i >= 0; i--) {
const nextDp = []
for (let j = 0; j < 3; j++) {
const nextRemain = nums[i] % 3
nextDp[j] = Math.max(nums[i] + dp[(nextRemain + j) % 3], dp[j])
}
dp = nextDp
}
return dp[0]
}
// another
/**
* @param {number[]} nums
* @return {number}
*/
const maxSumDivThree = function(nums) {
const sum = nums.reduce((ac, el) => ac + el, 0)
if(sum % 3 === 0) return sum
const remainder = sum % 3
const comp = 3 - remainder
nums.sort((a, b) => a - b)
const re = [], rc = []
for(let i = 0, len = nums.length; i < len; i++) {
if(nums[i] % 3 === remainder) {
if(re.length < 1) re.push(i)
}
if(nums[i] % 3 === comp) {
if(rc.length < 2) rc.push(i)
}
if(re.length === 1 && rc.length === 2) break
}
if(re.length === 1 && rc.length === 2) {
return Math.max(sum - nums[re[0]], sum - nums[rc[0]] - nums[rc[1]])
} else if(re.length === 1) {
return sum - nums[re[0]]
} else if(rc.length === 2) {
return sum - nums[rc[0]] - nums[rc[1]]
} else {
return 0
}
};