Last active
November 11, 2015 16:31
-
-
Save aquajach/d5ebe5dd833d6b27c0e0 to your computer and use it in GitHub Desktop.
Best stock strategy quiz
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
prices = [] | |
10.times do | |
prices << rand(1..100) | |
end | |
p "Today's prices are #{prices.join(', ')}" | |
min = max = prices.first | |
profit = 0 | |
buy_in_price = 0 | |
sell_price = 0 | |
best_profit = 0 | |
prices.each_with_index do |price, index| | |
if price > max | |
max = price | |
profit = price - min | |
end | |
if price < min || index == prices.length - 1 | |
if profit > best_profit | |
buy_in_price = min | |
sell_price = max | |
best_profit = profit | |
end | |
min = price | |
max = price | |
profit = 0 | |
end | |
end | |
if best_profit > 0 | |
p "The best strategy is to buy in at #{buy_in_price}, and sell at #{sell_price} to earn maximum profit as #{best_profit}" | |
else | |
p "You'd better do nothing today" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment