Last active
May 4, 2022 16:51
-
-
Save telekosmos/2be16b3f3730a0a6c2c1920bdb3584dd to your computer and use it in GitHub Desktop.
Most profit
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
You will be given a list of stock prices for a given day and your goal is to return the | |
maximum profit that could have been made by buying a stock at the given price and then selling the | |
stock later on. For example if the input is: [45, 24, 35, 31, 40, 38, 11] then your program should | |
return **16** because if you bought the stock at $24 and sold it at $40, a profit of $16 was made and | |
this is the largest profit that could be made. If no profit could have been made, return -1. | |
If the given array is {100, 180, 260, 310, 40, 535, 695}, the maximum profit can earned by buying | |
on day 0, selling on day 3 (+210). Again buy on day 4 and sell on day 6 (+650). If the given array of prices is | |
sorted in decreasing order, then profit cannot be earned at all. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from functools import reduce | |
def max_profit(values): | |
def one_diff(subvalues): | |
diff_list = [-subvalues[0] + e for e in subvalues[1::]] | |
return max(diff_list) if (len(diff_list) > 1) else 0 | |
return max([one_diff(values[i::]) for i in range(0, len(values))]) | |
""" | |
In [1]: max_profit([7, 6, 4 ,3 ,1]) | |
Out[79]: 0 | |
In [2]: max_profit([7,1,5,3,6,4]) | |
Out[80]: 5 | |
In [3]: max_profit([100, 180, 260, 310, 40, 535, 695]) | |
Out[3]: 655 | |
""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment