Created
September 2, 2020 06:57
-
-
Save arkadyark/b411e3d2347284587649a8e2b1e7307b to your computer and use it in GitHub Desktop.
Stock date problem from Cassidoo newsletter
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
''' | |
This week’s question: | |
Given an array of numbers that represent stock prices (where each number is the price for a certain day), find 2 days when you should buy and sell your stock for the highest profit. | |
Example: | |
$ stockBuySell([110, 180, 260, 40, 310, 535, 695]) | |
$ “buy on day 4, sell on day 7” | |
''' | |
def stockBuySell(prices): | |
buyDate = 0 | |
sellDate = 0 | |
buyPrice = prices[buyDate] | |
sellPrice = prices[sellDate] | |
profit = sellPrice - buyPrice | |
best = (buyDate, sellDate, buyPrice, sellPrice, profit) | |
while sellDate < len(prices) - 1: | |
sellDate += 1 | |
sellPrice = prices[sellDate] | |
if sellPrice < buyPrice: | |
buyDate = sellDate | |
buyPrice = prices[buyDate] | |
profit = sellPrice - buyPrice | |
if profit > best[4]: | |
best = (buyDate, sellDate, buyPrice, sellPrice, profit) | |
return best | |
def print_result(best): | |
buyDate, sellDate, buyPrice, sellPrice, profit = best | |
if profit == 0: | |
print("No profit can be made, do not buy") | |
else: | |
print("Buy on day {} for {}, sell on day {} for {}, make {} in profit".format(buyDate + 1, sellDate + 1, buyPrice, sellPrice, profit)) | |
if __name__ == "__main__": | |
best = stockBuySell([0, 1, 2, 3, 4]) # Buy on day 1, sell on day 5 | |
print_result(best) | |
best = stockBuySell([4, 3, 2, 1, 0]) # Don't buy | |
print_result(best) | |
best = stockBuySell([110, 180, 260, 40, 310, 535, 695]) # Buy on day 4, sell on day 7 | |
print_result(best) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment