Last active
June 2, 2019 11:41
-
-
Save iMel408/f2405a127c583de63d5a191c963bbf79 to your computer and use it in GitHub Desktop.
Figure out the optimal buy and sell point for a given stock, given its prices yesterday. No "shorting"—you need to buy before you can sell.
This file contains hidden or 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
def buy_low_sell_high(lst): | |
"""Figure out the optimal buy and sell point for a given stock, given its prices yesterday. | |
No "shorting"—you need to buy before you can sell. """ | |
min_buy = lst[0] | |
mx_gain = 0 | |
for i in range(len(lst)): | |
if lst[i] - min_buy >= mx_gain: | |
mx_gain = lst[i] - min_buy | |
if lst[i] <= min_buy: | |
min_buy = lst[i] | |
return mx_gain | |
print(buy_low_sell_high([10, 7, 5, 8, 11, 9])) # 5 & 11 = 6 | |
print(buy_low_sell_high([12, 10, 7, 3, 4, 33, 4, 8])) # 3 & 33 = 30 | |
print(buy_low_sell_high([30, 20, 10, 5])) # 0 gain | |
print(buy_low_sell_high([5, 10, 33, 4, 7])) # 5 & 33 = 28 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment