Skip to content

Commit 36bb06b

Browse files
authored
Create 1262. Greatest Sum Divisible by Three1 (#940)
2 parents 8b9dc58 + 476e1f9 commit 36bb06b

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
class Solution {
2+
public:
3+
int maxSumDivThree(vector<int>& nums) {
4+
int sum = 0;
5+
vector<int> r1, r2;
6+
7+
for(int x : nums){
8+
sum += x;
9+
if(x % 3 == 1) r1.push_back(x);
10+
else if(x % 3 == 2) r2.push_back(x);
11+
}
12+
13+
if(sum % 3 == 0) return sum;
14+
15+
sort(r1.begin(), r1.end());
16+
sort(r2.begin(), r2.end());
17+
18+
int rem = sum % 3;
19+
int ans = 0;
20+
21+
if(rem == 1){
22+
int op1 = (r1.size() >= 1 ? sum - r1[0] : 0);
23+
int op2 = (r2.size() >= 2 ? sum - r2[0] - r2[1] : 0);
24+
ans = max(op1, op2);
25+
}
26+
else{
27+
int op1 = (r2.size() >= 1 ? sum - r2[0] : 0);
28+
int op2 = (r1.size() >= 2 ? sum - r1[0] - r1[1] : 0);
29+
ans = max(op1, op2);
30+
}
31+
32+
return ans;
33+
}
34+
};

0 commit comments

Comments
 (0)