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
#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