如何解决Python:找到可以作为多集总和的最大数?
问题: 给定一个整数的多重集,找到我们可以得到的最大数作为这些整数的子多重集的总和,使得没有两个整数的绝对差为 1
例如:
- 如果多重集是
[1,1,2,3,4,5,15]
,
最大和是 (1+1+3+3+3+5+5+5 = 26) - 如果多重集是
[3,6,10,20]
,
最大和是 (3+3+5+5+5+5+10+20 = 56)
我的尝试:
这类似于另一个关于找到具有最大和的子集的问题,使得没有两个元素彼此相邻。对于那个特定的问题,我使用了动态编程方法并使用相同的方法来尝试解决这个问题,但没有成功。任何帮助将不胜感激!
from collections import Counter
def max_sum(nums):
c = Counter(nums)
N = sorted(set(nums))
if len(N) == 0:
return 0
if len(N) == 1:
return c[N[0]]*N[0]
if len(N) == 2:
return max(c[N[0]]*N[0],c[N[1]]*N[1])
dp = [0] * len(N)
dp[0] = c[N[0]]*N[0]
if (N[1] - N[0]) == 1:
dp[1] = max(c[N[0]]*N[0],c[N[1]]*N[1])
else:
dp[1] = sum([c[N[0]]*N[0],c[N[1]]*N[1]])
for i in range(2,len(N)):
if (N[i] - N[i-1]) == 1:
dp[i] = max(c[N[i]]*N[i] + dp[i-2],dp[i-1])
else:
dp[i] = dp[i-1] + c[N[i]]*N[i]
return dp[-1]
max_sum([1,6])
解决方法
我想这就是你要找的。不需要这么复杂的功能
add=[1,1,3,5,5]
adds.sort()
int_1=add[0] #=== First element of the list
new_list=[]
for i in range(len(add)):
if add[i]-int_1==1: #=== If difference is 1
new_list.append(add[i])
else:
int_1=add[i] #=== Update the variable if difference isn't 1
for i in new_list:
add.remove(i) #=== Remove from main list
print(' + '.join([str(yx) for yx in add])+" = ",sum(add))
输出:
1 + 1 + 3 + 3 + 3 + 5 + 5 + 5 = 26
如果你想在函数中使用它:
adds=[1,6,5]
adds.sort()
def max_sum(add):
new_list=[]
for i,j in zip(add[:-1],add[1:]): #--- Zip the 2 consecutive elements
if j-i==1: #=== If the difference between the numbers is 1
new_list.append(i) #=== Add to new_list
for i in new_list: #=== Iterate over the elements in the list
add.remove(i) #=== Remove those elements in the list
print(' + '.join([str(yx) for yx in add])+" = ",sum(add)) #=== join all elements in the list with a ' + '
max_sum(adds)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。