zoukankan      html  css  js  c++  java
  • 【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
  • 相关阅读:
    C++ 数组array与vector的比较
    C/C++头文件区别
    C/C++ 标准输入输出重定向
    C文件读写
    输入输出重定向
    【剑指offer26 二叉搜索树与双向链表】
    【剑指offer25 复杂链表的复制】
    【剑指offer23 二叉搜索树的后序遍历序列】
    【剑指offer22 从上往下打印二叉树 & 60 把二叉树打印成多行】
    【剑指offer21 栈的压入、弹出序列】
  • 原文地址:https://www.cnblogs.com/seyjs/p/11896223.html
Copyright © 2011-2022 走看看