Created
August 31, 2020 21:52
-
-
Save buckmaxwell/060da5c299c63baaa3395153f76d34ac to your computer and use it in GitHub Desktop.
2020.08.31
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
#!/usr/bin/env python3 | |
def stock_buy_sell(tst): | |
"""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.""" | |
i = len(tst) - 1 | |
high_idx, low_idx = i, i | |
window_high, window_low = i, i | |
largest_diff = 0 | |
while i >= 0: | |
window_low = i | |
if tst[i] > tst[window_high]: | |
window_high = i | |
current_diff = tst[window_high] - tst[window_low] | |
if current_diff > largest_diff: | |
high_idx = window_high | |
low_idx = window_low | |
largest_diff = tst[window_high] - tst[window_low] | |
i -= 1 | |
print(f"buy on day {low_idx + 1}, sell on day {high_idx+1}") | |
stock_buy_sell([110, 180, 260, 40, 310, 535, 695]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment