前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【LeetCode第 163 场周赛】5265. Greatest Sum Divisible by Three

【LeetCode第 163 场周赛】5265. Greatest Sum Divisible by Three

作者头像
韩旭051
发布2019-12-03 15:22:03
3200
发布2019-12-03 15:22:03
举报
文章被收录于专栏:刷题笔记刷题笔记

版权声明:本文为博主原创文章,遵循 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 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

动态规划,貌似我只会做这一道题,,,, ,

反正这个数被三除只有三种情况 整除 余1 余2,so只记录这三种情况最大和一直更新就OK啦

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;
    }
};
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-11-18 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 动态规划,貌似我只会做这一道题,,,, ,
  • 反正这个数被三除只有三种情况 整除 余1 余2,so只记录这三种情况最大和一直更新就OK啦
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档