Last active
August 29, 2015 14:12
-
-
Save gingeleski/edd0910ba650e1a61808 to your computer and use it in GitHub Desktop.
Takes an array of stock prices, assuming each entry represents successive daily averages, and determines what optimal buy and sell dates would've been.
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
# Takes an array of stock prices, assuming each entry | |
# represents average price on successive days, and | |
# determines what optimal buy and sell dates would've been. | |
def stock_picker(stock_prices_array) | |
hypothesis = [0,0,1] # [Hypothetical profit, buy time, sell time] | |
i = 0 | |
while i < stock_prices_array.length | |
if_buy = i | |
j = i unless stock_prices_array[i+1] == nil | |
break if stock_prices_array[i+1] == nil | |
while j < stock_prices_array.length | |
if_sell = j | |
if stock_prices_array[j] - stock_prices_array[i] > hypothesis[0] | |
hypothesis[0] = stock_prices_array[j] - stock_prices_array[i] | |
hypothesis[1] = i | |
hypothesis[2] = j | |
end | |
j += 1 | |
end | |
i += 1 | |
end | |
return hypothesis | |
end | |
# EXAMPLE | |
puts stock_picker([17,3,6,9,15,8,6,1,10]) | |
# Highest potential profit is 12 units if you buy at cell 1 price and | |
# sell at cell 4 price |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment