全组合会TLE,感觉是需要用DP,但是不会做。

找了一份参考答案,还在研究中。

 1 class Solution:
 2     def maxSumDivThree(self, nums: List[int]) -> int:
 3         n = len(nums)
 4         dp = [[0 for _ in range(n)] for _ in range(3)]
 5         dp[nums[0] % 3][0] = nums[0]
 6         for i in range(1, n):
 7             for r in range(3):
 8                 include = dp[(r - nums[i]) % 3][i-1] + nums[i]
 9                 if include % 3 == r:
10                     dp[r][i] = max(dp[r][i-1], include)
11                 else:
12                     dp[r][i] = dp[r][i-1]
13         return dp[0][n-1]

参考地址:https://leetcode.com/problems/greatest-sum-divisible-by-three/discuss/431105/Python-DP-solution

 

另外一个是使用数学方法解的:

 1 class Solution(object):
 2     def maxSumDivThree(self, nums):
 3         dict1={}
 4         sum1=sum(nums)
 5         for i in nums:
 6             g=i%3
 7             if g in dict1:
 8                 dict1[g].append(i)
 9             else:
10                 dict1[g]=[i]
11         if 1 in dict1:
12             dict1[1]=sorted(dict1[1],reverse=True)
13         
14         if 2 in dict1:
15             dict1[2]=sorted(dict1[2],reverse=True)
16         
17         
18         rem=sum1%3
19         if rem==0:
20             return sum1
21         
22         if rem==1:
23             if rem in dict1:
24                 max1=dict1[rem].pop()
25                 max2=1000000000
26                 if 2 in dict1 and len(dict1[2])>1:
27                     max1=dict1[2].pop()+dict1[2].pop()
28                 return sum1-min(max1,max2)
29             else:
30                 sum1-=dict1[2].pop()+dict1[2].pop()
31                 return sum1
32         else:
33             if rem in dict1:
34                 max1=dict1[2].pop()
35                 max2=1000000000
36                 if 1 in dict1 and len(dict1[1])>1:
37                     max2=dict1[1].pop()+dict1[1].pop()
38                 return sum1-min(max1,max2)
39             else:
40                 sum1-=dict1[1].pop()+dict1[1].pop()
41                 return sum1

参考地址:https://leetcode.com/problems/greatest-sum-divisible-by-three/discuss/431078/Python-simple-solution

 

总结:这种DP和数学的题目,是大厂笔试时很喜欢出的题型,需要很强的数学思维(发现题目中隐藏的规律)。

我对这种题目束手无策,基本上一见到就放弃,只能看看大神们的解决方案,争取有所领悟吧。

posted on 2019-11-17 12:30  Sempron2800+  阅读(269)  评论(0编辑  收藏  举报