Stock picker that tells when to buy and when to sell
The code is a pretty sensible solution for this problem.

Never put $ before a variable in Ruby, it becomes global and may be modified from anywhere.

I think that function programming is more apt to algorithmic problems than imperative. I solved it like this:

def stock(prices)
  ((0...prices.length).to_a)
    .repeated_permutation(2)
    .select {|start, finish| finish &gt; start}
    .max_by {|start, finish| prices[finish] - prices[start]}
end


It is more close to how you would describe the problem, anyway you may be intersted in PBRTM, the main programming style supported by Ruby. (Programming By Reading The Manual) Ruby gives you many many library functions and you may enjoy scrolling through them to find the ones that help you shorten your code.

Getting to the real meat, both yours and my approach run in O(N^2) time complexity. That means that for a million (10^6) stock prices, the code must make (10^12) operations, that is not feasible.

I suggest something like this:

I find min and max of array. Is max after min? If so I am done. Otherwise I delete the least far from average and start again.

This is almost linear, but may not be optimal.

OR

You may sort the data O(N log N) and try first and last, if in the array the index of last is after the index of first, done. Otherwise delete the least far from average between first and last and repeat. Also this may fail to provide the optimal result in edge cases.

All in all, a quadratic solution is easy but slow but a quasilinear one is hard but fast.