Home > Net >  Delete Max Sum of N Consecutive Numbers in Python?
Delete Max Sum of N Consecutive Numbers in Python?

Time:03-07

The purpose of this exercise is to delete a set of N numbers from a list which sum is the highest. The exercise is fairly simple but I am struggling with it. So it would be to convert:

list = [1, 4, 8, 2, 5]
N = 3

To

solved_list = [1, 4]

In this case, the the highest sum for N (3 numbers) is 8 5 2. Therefore, it is deleted from the list. This is what I have done so far:

def deletehighestsum(lst, n):
    current_max_numbers = lst[0:n]
    current_max = sum(lst[0:n])
    new_max = 0
    new_max_numbers = []
    for i in range(0, len(lst)):
        new_max = sum(lst[i:n i])
        if current_max < new_max:
            new_max_numbers = lst[i:n i]
    
    solved_list = [x for x in lst if x not in new_max_numbers]
    return solved_list

CodePudding user response:

You can use max on range with a custom key (sum of slices) to get the starting index of the max key, then slice:

l = [1, 4, 8, 2, 5]
N = 3

idx_max = max(range(0, len(l)-N 1), key=lambda x: sum(l[x:x 3]))
# 2

out = l[:idx_max] l[idx_max N:]

output: [1, 4]

CodePudding user response:

from itertools import combinations
l = [1,4,8,2,5]
n = 3
def deletehighestsum(arr,n):
    t = max({x:sum(x) for x in list(combinations(arr,n))})
    l = [i for i in arr if i not in t]
    return l
print(deletehighestsum(l,n))

what this solution does is basically checks for all the possible combinations of n integers within the list and then creates a dictionary with the tuple of possible integers as the key and their sum as the value and then checks for the tuple with the maximum sum
after that it creates a list which does not have the integers from the tuple and returns it
hope this helps

  • Related