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

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]

>Solution :

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])
  print(sum(x for x in nums if x>0))

Leave a Reply