Created
September 2, 2015 07:58
-
-
Save patcullen/9e69427bb3afee7241e8 to your computer and use it in GitHub Desktop.
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
=begin | |
A simple algorithm, not the most efficient*, can be explained as: | |
Iterate through every element in the array; call the current one "outer": | |
For every element after "outer", Step through and compare to "outer" | |
If the difference is larger than previously compared, store the result. | |
At the end, show the largest difference. | |
I read up on a few more advanced algorithms that should be more efficient, | |
however I managed to break the two I tried fairly easily. So I sticking with | |
simple. | |
=end | |
stock = [5, 6, 4, 7, 9, 8, 8, 11, 2] | |
difference = 0 | |
minimum = 0 | |
(0..stock.length - 1).each do |outer| | |
(outer + 1..stock.length - 1).each do |inner| | |
if stock[inner] - stock[outer] > difference then | |
difference = stock[inner] - stock[outer] | |
minimum = stock[outer] | |
end | |
end | |
end | |
puts "Best to buy the stock at #{minimum}, sell it at $#{minimum + difference}, for a profit of $#{difference}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment