Leetcode 1262. Greatest Sum Divisible by Three
Posted SnailTyan
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 1262. Greatest Sum Divisible by Three相关的知识,希望对你有一定的参考价值。
文章作者:Tyan
博客:noahsnail.com | CSDN | 简书
1. Description
2. Solution
**解析:**Version 1,是对Version 3的简化,具体参考Version 3。Version 2,先对数组求总和,然后根据每个数除3
的余数进行有序分组,当总和除3
余1
时,此时总和应该减去最小的余数为1
的数,或者减去最小的两个余数为2
的数,如果二者同时有,则取二者的最小值,余数为2
时同理。Version 3,dp
用来维护最大和除3
余数分别为0,1,2
的状态,初始时,当余数为0
时,不影响dp[0]
的值,不需要更新dp[1],dp[2]
,当余数为1,2
时,此时才需要开始更新dp[1],dp[2]
,然后根据余数的值不同,对各状态进行更新,pre
用来保存上一轮结束时的状态。
- Version 1
class Solution:
def maxSumDivThree(self, nums: List[int]) -> int:
n = len(nums)
stat = [0, 0, 0]
for i in range(n):
for x in stat[:]:
remainder = (x + nums[i]) % 3
stat[remainder] = max(stat[remainder], x + nums[i])
return stat[0]
- Version 2
class Solution:
def maxSumDivThree(self, nums: List[int]) -> int:
total = sum(nums)
n = len(nums)
one = []
two = []
for i in range(n):
if nums[i] % 3 == 1:
bisect.insort(one, nums[i])
elif nums[i] % 3 == 2:
bisect.insort(two, nums[i])
if total % 3 == 1:
if len(one) == 0:
total -= (two[0] + two[1])
elif len(two) < 2:
total -= one[0]
else:
total -= min(one[0], two[0] + two[1])
elif total % 3 == 2:
if len(two) == 0:
total -= (one[0] + one[1])
elif len(one) < 2:
total -= two[0]
else:
total -= min(one[0] + one[1], two[0])
return total
- Version 3
class Solution:
def maxSumDivThree(self, nums: List[int]) -> int:
dp = [0, -float('inf'), -float('inf')]
for num in nums:
pre = dp[:]
if num % 3 == 0:
dp[0] = max(pre[0] + num, pre[0])
dp[1] = max(pre[1] + num, pre[1])
dp[2] = max(pre[2] + num, pre[2])
elif num % 3 == 1:
dp[0] = max(pre[2] + num, pre[0])
dp[1] = max(pre[0] + num, pre[1])
dp[2] = max(pre[1] + num, pre[2])
else:
dp[0] = max(pre[1] + num, pre[0])
dp[1] = max(pre[2] + num, pre[1])
dp[2] = max(pre[0] + num, pre[2])
return dp[0]
Reference
以上是关于Leetcode 1262. Greatest Sum Divisible by Three的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode --- 1071. Greatest Common Divisor of Strings 解题报告
LeetCode.1071-字符串最大公约数(Greatest Common Divisor of Strings)
[LeetCode] 1431. Kids With the Greatest Number of Candies
[LeetCode] 1431. Kids With the Greatest Number of Candies