classSolution(object): defmaxSumDivThree(self, nums): """ :type nums: List[int] :rtype: int """ # 先排序易於操作 nums.sort() smv = sum(nums) # 餘數相同者各自進 list dic = defaultdict(list) for c in nums: t = c%3 dic[t].append(c) div = smv%3
# 取最小、次小值在各餘數狀況下 for c in nums: d = c%3 if d == 1: if c <= div1[0]: if c < div1[1]: div1[0] = div1[1] div1[1] = c else: div1[0] = c elif d == 2: if c <= div2[0]: if c < div2[1]: div2[0] = div2[1] div2[1] = c else: div2[0] = c smv = sum(nums) div = smv%3
# 總和即滿足,直接 return if div == 0: return smv # 缺 1 可由砍掉 1 個 1 或 2 個 2 來滿足題意 if div == 1: if div1[1] != inf and div2[0] != inf: return smv - min(div1[1], sum(div2)) elif div1[1] != inf: return smv - div1[1] else: if div2[0] != inf: return smv - sum(div2) # 缺 2 可由砍掉 1 個 2 或 2 個 1 來滿足題意 elif div == 2: if div2[1] != inf and div1[0] != inf: return smv - min(div2[1], sum(div1)) elif div2[1] != inf: return smv - div2[1] else: if div1[0] != inf: return smv - sum(div1) # 皆無法完成者 return0
classSolution(object): defmaxSumDivThree(self, nums): """ :type nums: List[int] :rtype: int """ smv = sum(nums) if smv % 3 == 0: return s inf = float("inf") r11 = inf r12 = inf r21 = inf r22 = inf for num in nums: if num % 3 == 1and num < r12: if num < r11: r12 = r11 r11 = num else: r12 = num if num % 3 == 2and num < r22: if num < r21: r22 = r21 r21 = num else: r22 = num if smv % 3 == 1: return smv - min(r11, r21+r22) if smv % 3 == 2: return smv - min(r21, r11+r12)
Complexity
Time Complexity: O(n)
只走過 n 個數字數次
Space Complexity: O(1)
只看餘 0, 1, 2 且至多兩個
DP
思路
from wangy666,以 DP 解之,dp[i][j] 表示前 i 個數總和數餘 j 之最大結果