class Solution:
def maxSumDivThree(self, nums: List[int]) -> int:
self.res = 0
def backtrack(temp, start):
total = sum(temp)
if total % 3 == 0:
self.res = max(self.res, total)
for i in range(start, len(nums)):
temp.append(nums[i])
backtrack(temp, i + 1)
temp.pop(-1)
backtrack([], 0)
return self.res
class Solution:
def maxSumDivThree(self, nums: List[int]) -> int:
one = []
two = []
total = 0
for num in nums:
total += num
if num % 3 == 1:
one.append(num)
if num % 3 == 2:
two.append(num)
one.sort()
two.sort()
if total % 3 == 0:
return total
elif total % 3 == 1 and one:
if len(two) >= 2 and one[0] > two[0] + two[1]:
return total - two[0] - two[1]
return total - one[0]
elif total % 3 == 2 and two:
if len(one) >= 2 and two[0] > one[0] + one[1]:
return total - one[0] - one[1]
return total - two[0]
return 0
class Solution:
def maxSumDivThree(self, nums: List[int]) -> int:
one = [float('inf')] * 2
two = [float('inf')] * 2
total = 0
for num in nums:
total += num
if num % 3 == 1:
if num < one[0]:
t = one[0]
one[0] = num
one[1] = t
elif num < one[1]:
one[1] = num
if num % 3 == 2:
if num < two[0]:
t = two[0]
two[0] = num
two[1] = t
elif num < two[1]:
two[1] = num
if total % 3 == 0:
return total
elif total % 3 == 1 and one:
if len(two) >= 2 and one[0] > two[0] + two[1]:
return total - two[0] - two[1]
return total - one[0]
elif total % 3 == 2 and two:
if len(one) >= 2 and two[0] > one[0] + one[1]:
return total - one[0] - one[1]
return total - two[0]
return 0
class Solution:
def maxSumDivThree(self, nums: List[int]) -> int:
state = [0, float('-inf'), float('-inf')]
for num in nums:
if num % 3 == 0:
state = [state[0] + num, state[1] + num, state[2] + num]
if num % 3 == 1:
a = max(state[2] + num, state[0])
b = max(state[0] + num, state[1])
c = max(state[1] + num, state[2])
state = [a, b, c]
if num % 3 == 2:
a = max(state[1] + num, state[0])
b = max(state[2] + num, state[1])
c = max(state[0] + num, state[2])
state = [a, b, c]
return state[0]
class Solution:
def maxSumDivThree(self, nums: List[int]) -> int:
state = [0, float('-inf'), float('-inf')]
for num in nums:
temp = [0] * 3
for i in range(3):
temp[(i + num) % 3] = max(state[(i + num) % 3], state[i] + num)
state = temp
return state[0]