版权声明:本文为博主原创文章,遵循 CC 4.0 BY 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/shiliang97/article/details/103117758
5265. Greatest Sum Divisible by Three
Given an array nums of integers, we need to find the maximum possible sum of elements of the array such that it is divisible by three.
Example 1:
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:
Input: nums = [4] Output: 0 Explanation: Since 4 is not divisible by 3, do not pick any number. Example 3:
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 <= nums.length <= 4 * 10^4 1 <= nums[i] <= 10^4
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/greatest-sum-divisible-by-three 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution {
public:
int maxSumDivThree(vector<int>& nums) {
int one=0;
int two=0;
int three=0;
for(int i=0;i<nums.size();i++){
int a=nums[i]+one;
int b=nums[i]+two;
int c=nums[i]+three;
if(a%3==0){
if(a>three){
three=a;
}
}else if(a%3==1){
if(a>one){
one=a;
}
}else if(a%3==2){
if(a>two){
two=a;
}
}
if(b%3==0){
if(b>three){
three=b;
}
}else if(b%3==1){
if(b>one){
one=b;
}
}else if(b%3==2){
if(b>two){
two=b;
}
}
if(c%3==0){
if(c>three){
three=c;
}
}else if(c%3==1){
if(c>one){
one=c;
}
}else if(c%3==2){
if(c>two){
two=c;
}
}
//cout<<one<<" "<<two<<" "<<three<<endl;
}
return three;
}
};