Skip to content

Instantly share code, notes, and snippets.

@patcullen
Created September 2, 2015 07:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save patcullen/9e69427bb3afee7241e8 to your computer and use it in GitHub Desktop.
Save patcullen/9e69427bb3afee7241e8 to your computer and use it in GitHub Desktop.
=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