Search code examples
pythonalgorithmlistsub-array

How to sum the two largests elements in a list?


I have a list like this:

[1, 2, 5, 2, 7, 3, 9, 5...]

Is there an effective way to find the sum of the 2 largest elements here without:

for i in range():
    for j in range():

I've found this: "Maximum subarray problem"

But I've not completely understand what it does.


Solution

  • sum(sorted([9,8,1,3,4,5,7,0])[-2:])
    
    1. sorted all elements
    2. get two last elements
    3. sum it