How do I find the combination of values in an array that gives the highest sum

Question:

I’m trying to write a code that takes an array of integers, then returns the maximum sum you can get from different combinations of the values in the integer.
I also want to be able to see the particular combination that gives this as well.
And with the logic behind it if possible

What I tried didn't work
I'm expecting something like this:
For instance, in [1,2,3,4], the answer will be 10 with list:[1,2,3,4]
with [2,-3,7,-4,9], the answer will be 18 with [2,7,9]
and with [3, -4, -1, -3, ], the answer will be 2 with [3,-1]
Asked By: Divine

||

Answers:

The simple solution is to sum every positive number in the list:

print(sum(x for x in nums if x>0))

If you always need to add at least 2 numbers, then one option is to sort the list, and if the second last number is negative, add the last 2 numbers together:

nums = [3, -4, -1, -3]

nums = sorted(nums)

if nums[-2] < 0:
  print(nums[-2] + nums[-1])
else:
  print(sum(x for x in nums if x>0))
Answered By: match

The largest sum will contain all the positive numbers. If there are fewer than two positive numbers the use then two largest numbers (i.e. last two in ascending order):

numbers = [2,-3,7,-4,9]
result  = [n for n in numbers if n>0]
if len(result) < 2:
   result = sorted(numbers)[-2:]  # only sort when needed

# result: [2, 7, 9]  
# sum(result) : 18
Answered By: Alain T.
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.