LeetCode 1262. Greatest Sum Divisible by Three DP坑

231 篇文章 0 订阅

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

---------------------------------

It's easy to come up with DP, the right codes:

class Solution:
    def maxSumDivThree(self, nums):
        #pre0
        #f[0][j] = max(f[0][j-1]+num if num % 3 == 0 else f[0][j-1],...)
        sum0,sum1,sum2 = 0,0,0
        for num in nums:
            for nxt in [sum0+num,sum1+num,sum2+num]:
                if (nxt % 3 == 0):
                    sum0 = max(sum0, nxt)
                elif (nxt % 3 == 1):
                    sum1 = max(sum1, nxt)
                elif (nxt % 3 == 2):
                    sum2 = max(sum2, nxt)
        return sum0
s = Solution()
print(s.maxSumDivThree([3,6,5,1,8]))

But it's also easy to write bug codes like:

class Solution:
    def maxSumDivThree(self, nums):
        #pre0 
        #f[0][j] = max(f[0][j-1]+num if num % 3 == 0 else f[0][j-1],...)
        sum0,sum1,sum2 = 0,0,0
        for num in nums:
            d0,d1,d2 = 0,0,0
            mod = num % 3
            if (mod == 0):
                d0 = num
            elif (mod == 1):
                d1 = num
            else:
                d2 = num
            n0 = max(sum0+d0, sum1+d2, sum2+d1)
            n1 = max(sum0+d1, sum1+d0, sum2+d2)
            n2 = max(sum0+d2, sum1+d1, sum2+d0)
            sum0,sum1,sum2 = n0,n1,n2
        return sum0
s = Solution()
print(s.maxSumDivThree([1,2,3,4,4]))

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值