Last active
May 20, 2018 21:08
-
-
Save lopezm1/cdb3f961a3a91799c1126e0ff0e44303 to your computer and use it in GitHub Desktop.
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
# The cost of a stock on each day is given in an array, find the max profit that you can make by buying and selling in those days. For example, 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. Again buy on day 4 and sell on day 6. If the given array of prices is sorted in decreasing order, then profit cannot be earned at all. | |
def sell(lowidx, highidx): | |
print("time to sell -------") | |
print("buy:", lowidx) | |
print("sell:", highidx) | |
def stock(arr): | |
low = None # keep track of lowest value | |
lowidx = None # keep track of lowest day | |
high = None | |
highidx = None | |
for idx, x in enumerate(arr[:-1]): | |
if low is None: # first lowest stock | |
low = arr[idx] | |
lowidx = idx | |
print("first low", low) | |
elif arr[idx] < low: # new lowest stock | |
low = arr[idx] | |
lowidx = idx | |
print("low",low) | |
if high is None and arr[idx+1] > low: # find first high | |
high = arr[idx+1] | |
highidx = idx+1 | |
print("first high", high) | |
elif high is not None and arr[idx+1] > high : # new highest stock | |
high = arr[idx+1] | |
highidx = idx+1 | |
print("high:", high) | |
if arr[idx + 1] < arr[idx] and high is not None: # let's sell mid week | |
sell(lowidx, highidx) | |
lowidx = None | |
highidx = None | |
sell(lowidx, highidx) # sell on final day | |
stock([100, 80, 180, 260, 310, 40, 535, 695]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment