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]))