【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