Last active
August 29, 2015 14:20
-
-
Save vike27/7ac2ace1e6996a86acef to your computer and use it in GitHub Desktop.
Maximum Profit Stock Market Problem Algorithm
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
Writing coding interview questions hasn't made me rich. Maybe trading Apple stocks will. | |
I have 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). | |
#Solution | |
def max_profit(stock_prices_yesterday) | |
i = 0 | |
global_max = stock_prices_yesterday[1] - stock_prices_yesterday[0] | |
while i < stock_prices_yesterday.length - 1 do | |
j = 1 | |
while j < (stock_prices_yesterday.length - i) do | |
local_max = stock_prices_yesterday[i + j] - stock_prices_yesterday[i] | |
if local_max > global_max | |
global_max = local_max | |
end | |
j += 1 | |
end | |
i += 1 | |
end | |
global_max | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment