Created
December 29, 2016 03:32
-
-
Save abadfish/a732ba0fcc424dd5a9f14a5f41e41036 to your computer and use it in GitHub Desktop.
Technical Question from Mock Interview with Funnel interviewer Bradley Gunn
This file contains hidden or 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
def biggest_loss(prices) | |
max_loss = 0 | |
prices.each_with_index do |px1, day| # n days as index | |
for px2 in prices[day+1..-1] # iterate through all days once | |
potential_loss = px1 - px2 # buy at price 1 and sell at price 2 | |
if potential_loss > max_loss | |
max_loss = potential_loss | |
end | |
end | |
end | |
max_loss | |
end | |
test_1 = [ 14, 1, 18, 23, 12, 8, 16 ] | |
test_2 = [ 18, 5, 19, 7 ] | |
biggest_loss(test_1) | |
# => 15 | |
biggest_loss(test_2) | |
# => 13 | |
# Let’s say you are given an array of n integers, which represents the prices | |
# of a stock over n consecutive days. | |
# Please write a function in the language of your choice that returns the | |
# biggest loss you could incur over those n days by buying high and selling low. | |
# For example: if the array contains |14|1|18|23|12|8|16|, then the biggest | |
# possible loss is $15 (buying at $23 and selling at $8). | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment