Python:找到作为多个集合的和可以得到的最大数?

Python:找到作为多个集合的和可以得到的最大数?,python,arrays,algorithm,data-structures,dynamic-programming,Python,Arrays,Algorithm,Data Structures,Dynamic Programming,问题: 给定一个多重整数集,求出这些整数的子多重整数集之和所能得到的最大数,这样就没有两个整数的绝对差为1 例如: 如果多集是[1,1,2,3,3,3,4,4,5,5,15],最大和为(1+1+3+3+3+5+5=26) 如果多集是[3,3,4,4,4,5,5,5,5,6,6,10,20],最大和为(3+3+5+5+5+5+10+20=56) 我的尝试: 这类似于另一个问题,即寻找具有最大和的子集,使得没有两个元素彼此相邻。对于这个特定的问题,我使用了一种动态规划方法,并使用同样的方法试图解决这

问题: 给定一个多重整数集,求出这些整数的子多重整数集之和所能得到的最大数,这样就没有两个整数的绝对差为1

例如:

  • 如果多集是
    [1,1,2,3,3,3,4,4,5,5,15]

    最大和为(1+1+3+3+3+5+5=26)
  • 如果多集是
    [3,3,4,4,4,5,5,5,5,6,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,1,1,5,5,5,6,6,6])
    

    我想这就是你要找的。不需要这样复杂的函数

    add=[1,1,3,3,3,5,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,1,3,3,3,5,5,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)
    

    如果列表中的第一个元素不应该是最大和的一部分,则函数将失败。如果输入列表未排序,它也会失败。现在@rdas可以了吗?你能解释一下你的代码吗?时间复杂度是多少?这是不正确的为什么?出了什么问题:(