【leetcode】1262. 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

解题思路:记sum为nums的和,如果其不能被3整除,那么余数只能是1或者2。如果余数是1,那么只需要减去nums中最小的除以3余数为1的数,或者减去nums中两个最小的除以3余数为2的数即可,两者之间选择较小的那个;如果余数是2,也同理。

代码如下:

复制代码
class Solution(object):
    def maxSumDivThree(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        total = sum(nums)
        if total % 3 == 0:return total
        nums.sort()
        list_1 = []
        list_2 = []
        for i in nums:
            if i % 3 == 1 and len(list_1) < 2:
                list_1.append(i)
            elif i % 3 == 2 and len(list_2) < 2:
                list_2.append(i)
        if total % 3 == 1:
            minus = float('inf')
            if len(list_1) > 0:
                minus = list_1[0]
            if len(list_2) == 2:
                minus = min(minus,list_2[0] + list_2[1])
        elif total % 3 == 2:
            minus = float('inf')
            if len(list_2) > 0:
                minus = list_2[0]
            if len(list_1) == 2:
                minus = min(minus, list_1[0] + list_1[1])
        if minus == float('inf'):return 0
        return total - minus
复制代码

 

posted @   seyjs  阅读(568)  评论(0编辑  收藏  举报
编辑推荐:
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
· C++代码改造为UTF-8编码问题的总结
· DeepSeek 解答了困扰我五年的技术问题
阅读排行:
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· 清华大学推出第四讲使用 DeepSeek + DeepResearch 让科研像聊天一样简单!
· 实操Deepseek接入个人知识库
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
点击右上角即可分享
微信分享提示