Created
May 20, 2018 21:03
-
-
Save lopezm1/574e23cdf62891b75e3822fd5ee9bf85 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 | |
lowidx = None | |
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 arr[idx+1] > high: # new highest stock | |
high = arr[idx+1] | |
highidx = idx+1 | |
print("high:", high) | |
if arr[idx + 1] < arr[idx]: # let's sell mid week | |
sell(lowidx, highidx) | |
lowidx = None | |
highidx = None | |
sell(lowidx, highidx) # sell on final day | |
stock([100, 180, 260, 310, 40, 535, 695]) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment