Skip to content

Instantly share code, notes, and snippets.

@buckmaxwell
Created August 31, 2020 21:52
Show Gist options
  • Save buckmaxwell/060da5c299c63baaa3395153f76d34ac to your computer and use it in GitHub Desktop.
Save buckmaxwell/060da5c299c63baaa3395153f76d34ac to your computer and use it in GitHub Desktop.
2020.08.31
#!/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