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

Find the highest triplet

I’m trying to create a function that receives a input list and return the sum of the highest triplet.
Not sure why but the following function doesn’t work when I run the tests on HackerRank.

Constraints:

1≤ n ≤4000
1≤ profit[I] ≤ 10^9

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

#Input samples:
#profit = [2, 10, 33, 2, 5]  # here, the result should be 5+10+33 = 48
#profit = [2, 1, 33, -6, 5, 10, 10]  # here, the result should be 5+10+33 = 48

def getMaximumProfit(profit):
    # Debug the below code to return the required output.
    maxi = 0
    for i in range(len(profit)-2):
        total = sum(profit[i:i+3])
        if maxi > total:
            maxi += total
        total = 0
    return total

>Solution :

You can take advantage of the sorted(list) method.
By sorting the list in reverse and getting the first 3 values, we can add up these values to get the highest possible number derived from 3 values in the input list:

def getMaximumProfit(profit):
    # Get all 3 highest integers
    returnVal: int = 0
    highest = sorted(profit, reverse=True)[:3]
    for value in highest:
        returnVal += value # Add all integers
    return returnVal
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