Skip to content

Instantly share code, notes, and snippets.

@mrchocoborider
Last active September 6, 2018 03:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrchocoborider/88c1e799a2da3f3241c1f28e9fdde5d6 to your computer and use it in GitHub Desktop.
Save mrchocoborider/88c1e799a2da3f3241c1f28e9fdde5d6 to your computer and use it in GitHub Desktop.
Interviewcake.com algorithmic pattern practice #1, Parker's solution.
def get_max_profit(stock_prices):
if len(stock_prices) < 2:
raise ValueError('Getting a profit requires at least 2 prices')
# We'll greedily update min_price and max_profit, so we initialize
# them to the first price and the first possible profit
min_price = stock_prices[0]
max_profit = stock_prices[1] - stock_prices[0]
# Start at the second (index 1) time
# We can't sell at the first time, since we must buy first,
# and we can't buy and sell at the same time! # If we started at index 0,
#we'd try to buy *and* sell at time 0.
# This would give a profit of 0, which is a problem if our
# max_profit is supposed to be *negative* - we'd return 0.
for current_time in xrange(1, len(stock_prices)):
current_price = stock_prices[current_time]
# See what our profit would be if we bought at the
# min price and sold at the current price potential_profit = current_price - min_price
# Update max_profit if we can do better
max_profit = max(max_profit, potential_profit)
# Update min_price so it's always # the lowest price we've seen so far
min_price = min(min_price, current_price) return max_profit
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment