1388 Greatest Sum Divisible By Three
1388 Greatest Sum Divisible By Three
Greatest Sum Divisible by Three 
Given an integer array nums, return the **maximum possible sum **of elements of the array such that it is divisible by three.
Example 1:
1
2
3
4
**Input:** nums = [3,6,5,1,8]
**Output:** 18
**Explanation:** Pick numbers 3, 6, 1 and 8 their sum is 18 (maximum sum divisible by 3).
Example 2:
1
2
3
4
5
**Input:** nums = [4]
**Output:** 0
**Explanation:** Since 4 is not divisible by 3, do not pick any number.
Example 3:
1
2
3
4
5
**Input:** nums = [1,2,3,4,4]
**Output:** 12
**Explanation:** Pick numbers 1, 3, 4 and 4 their sum is 12 (maximum sum divisible by 3).
Constraints:
1
2
1 <= nums.length <= 4 * 104
1 <= nums[i] <= 104
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
use std::cmp::max;
impl Solution {
pub fn max_sum_div_three(mut nums: Vec<i32>) -> i32 {
// add all
// remove the 2 1s
// remove 1 2s
// remove 1s
let mut s = 0;
let mut one : Vec<i32> = Vec::new();
let mut two : Vec<i32> = Vec::new();
nums.sort();
for k in nums {
s += k;
if k % 3 == 1 {
one.push(k)
}
if k % 3 == 2 {
two.push(k)
}
}
//print!("{} {} {}", one1, two1, two2);
if s % 3 == 0 {
return s;
}
//print!("{} {} {}", one1, two1, two2);
if s % 3 == 1 {
if one.len() > 0 && two.len() > 1 {
return max(s - one[0] , s - two[0] - two[1]);
} else if one.len() > 0 {
return s - one[0];
} else if two.len() > 1 {
return s - two[0] - two[1]
} else {
return 0;
}
}
//print!("{} {} {} {}", one1, two1, two2, s);
if s % 3 == 2 {
if two.len() > 0 && one.len() > 1 {
return max(s - two[0] , s - one[0] - one[1]);
} else if two.len() > 0 {
return s - two[0];
} else if one.len() > 1 {
return s - one[0] - one[1]
} else {
return 0;
}
}
return 0;
}
}
This post is licensed under CC BY 4.0 by the author.