Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading