Leetcode 1388 Solution
This article provides solution to leetcode question 1388 (greatest-sum-divisible-by-three)
Access this page by simply typing in "lcs 1388" in your browser address bar if you have bunnylol configured.
Leetcode Question Link
https://leetcode.com/problems/greatest-sum-divisible-by-three
Solution
class Solution:
def maxSumDivThree(self, nums: List[int]) -> int:
s = sum(nums)
r = s % 3
if r == 0:
return s
def find_one_small_num(r):
nonlocal nums
opt = None
for num in nums:
if num % 3 != r:
continue
if opt is None or opt > num:
opt = num
return opt and [opt]
def find_two_small_nums(r):
nonlocal nums
opt1 = None
opt2 = None
for num in nums:
if num % 3 != r:
continue
if opt1 is None or opt1 > num:
opt2 = opt1
opt1 = num
elif opt2 is None or opt2 > num:
opt2 = num
return opt1 and opt2 and [opt1, opt2]
answers = []
if r == 1:
opts = find_one_small_num(1)
if opts is not None:
answers.append(s - sum(opts))
opts = find_two_small_nums(2)
if opts is not None:
answers.append(s - sum(opts))
elif r == 2:
opts = find_one_small_num(2)
if opts is not None:
answers.append(s - sum(opts))
opts = find_two_small_nums(1)
if opts is not None:
answers.append(s - sum(opts))
return max(answers)