​LeetCode解法汇总1262. 可被三整除的最大和

 目录链接:

力扣编程题-解法汇总_分享+记录-CSDN博客

GitHub同步刷题项目:

https://github.com/September26/java-algorithms

原题链接:力扣


描述:

给你一个整数数组 nums,请你找出并返回能被三整除的元素最大和。

示例 1:

输入:nums = [3,6,5,1,8]
输出:18
解释:选出数字 3, 6, 1 和 8,它们的和是 18(可被 3 整除的最大和)。

示例 2:

输入:nums = [4]
输出:0
解释:4 不能被 3 整除,所以无法选出数字,返回 0。

示例 3:

输入:nums = [1,2,3,4,4]
输出:12
解释:选出数字 1, 3, 4 以及 4,它们的和是 12(可被 3 整除的最大和)。

提示:

  • 1 <= nums.length <= 4 * 10^4
  • 1 <= nums[i] <= 10^4

解题思路:

/**
 * 1262. 可被三整除的最大和
 * 解题思路:
 * 首先求出nums的和sum,看距离3的倍数是需要减1还是减2。
 * 如果需要减2,则分成2个1和1个2两种,如果需要减1,则分成2个2和1个1两种。
 * 然后nums从小打大排序,我们只需要找2个除以3余1的数或者1个除以3余2的数。求两者较小的那个。
 * 然后sum减掉这较小的那个,就是最终的结果。
 */

 

代码:

class Solution1262
{
public:
    int maxSumDivThree(vector<int> &nums)
    {
        int sum = 0;
        for (int i = 0; i < nums.size(); i++)
        {
            sum += nums[i];
        }
        if (sum % 3 == 0)
        {
            return sum;
        }
        int remainder1Num = 0;
        int remainder1Sum = 0;
        int remainder2Num = 0;
        int remainder2Sum = 0;
        if (sum % 3 == 1)
        {
            remainder1Num = 1;
            remainder2Num = 2;
        }
        else
        {
            remainder1Num = 2;
            remainder2Num = 1;
        }

        sort(nums.begin(), nums.end());
        for (int i = 0; i < nums.size(); i++)
        {
            if (nums[i] % 3 == 0)
                continue;
            if (nums[i] % 3 == 1)
            {
                if (remainder1Num > 0)
                {
                    remainder1Num--;
                    remainder1Sum += nums[i];
                }
            }
            else
            {
                if (remainder2Num > 0)
                {
                    remainder2Num--;
                    remainder2Sum += nums[i];
                }
            }
            if (remainder1Num == 0 && remainder2Num == 0)
            {
                break;
            }
        }
        if (remainder1Num > 0 && remainder2Num > 0)
        {
            return 0;
        }
        if (remainder1Num > 0)
        {
            return sum - remainder2Sum;
        }
        if (remainder2Num > 0)
        {
            return sum - remainder1Sum;
        }
        return sum - min(remainder2Sum, remainder1Sum);
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

失落夏天

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值