题目链接:1262. 可被三整除的最大和 - 力扣(LeetCode)
题目的意思是要找数组元素的最大和,这个和必须能被三整除
对于一个和来说,它和三整除就只有三个结果,0,1,2,可以在遍历数组中记录和模3三种结果的最大值
class Solution {
public:
int maxSumDivThree(vector<int> &nums) {
int remains[3] = {0};
int zero, one, two;
for (int num: nums) {
zero = remains[0] + num;
one = remains[1] + num;
two = remains[2] + num;
remains[zero % 3] = max(remains[zero % 3], zero);
remains[one % 3] = max(remains[one % 3], one);
remains[two % 3] = max(remains[two % 3], two);
}
return remains[0];
}
};