DEV Community

loading...

Discussion on: Daily Challenge #228 - Best Profit in Single Sale

Collapse
vidit1999 profile image
Vidit Sarkar

Here is a short Python recursive solution,

def max_profit(prices: list) -> int:
    if(len(prices) == 2):
        return prices[1] - prices[0]
    return max(prices[-1] - min(prices[:-1]), max_profit(prices[:-1]))

Test Cases,

print(max_profit([3, 10, 8, 4])) # output -> 7
print(max_profit([10, 7, 5, 8, 11, 9])) # output -> 6
print(max_profit([3, 4])) # output -> 1
print(max_profit([9, 9])) # output -> 0
print(max_profit([10, 7, 5, 4, 1])) # output -> -1