Created
April 7, 2015 06:45
-
-
Save netsprout/5d66db7c1cff100ffef0 to your computer and use it in GitHub Desktop.
Max Profit In Single Day Stock Prices
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
# There is an array stock_prices_yesterday where: | |
# * The indices are the time in minutes past trade opening time, which was 9:30am local time. | |
# * The values are the price in dollars of Apple stock at that time. | |
# For example, the stock cost $500 at 10:30am, so stock_prices_yesterday[60] = 500. | |
# Write an efficient algorithm for computing the best profit I could have made from 1 purchase and 1 sale of 1 Apple stock yesterday. | |
# No "shorting"—you must buy before you sell. You may not buy and sell in the same time step (at least 1 minute must pass). | |
def get_max_profit(stock_prices_yesterday) | |
min_price = stock_prices_yesterday[0] | |
max_profit = 0 | |
stock_prices_yesterday.each do |current_price| | |
# ensure min_price is the lowest price we've seen so far | |
min_price = [min_price, current_price].min | |
# 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_profit, potential_profit].max | |
end | |
max_profit | |
end | |
stock_prices_yesterday = [500,200,600,100,150,155,156,158,159,163,160,200,300] | |
puts "Your max profit is #{get_max_profit(stock_prices_yesterday)}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment