Stock picker that tells when to buy and when to sell The task of this project was to create a method that takes in an array of stock prices, one for each hypothetical day. From there, the method should return the best day to buy and the best day to sell the stock to maximize return. 

A few ground rules: 


Stocks need to be bought before they can be sold
It is possible that the lowest priced day can be the last day, and the highest price day could be the first day. 


With that, and a relatively new working knowledge of Ruby, here's what I came up with. It works, but I'm sure there could be improvements. Be gentle! 

def stock_prices (array)
    $largest_difference = 0
    array.each_with_index {|value, index|
        array.each {|i| 
            $difference = value -  i
            if ($difference &lt;= $largest_difference) &amp;&amp; (index &lt; array.rindex(i))
                $negative_array = [] &lt;&lt; $difference
                $negatives = [index, array.rindex(i)]
                $largest_difference = $difference
            end
        }   
    }
    if $negative_array.nil?
        puts "The stock should be bought and sold at [0, 1], respectively"
    else
        puts "The stock should be bought and sold at #{$negatives}, respectively"
    end
end

stock_prices([17,3,6,9,15,8,6,1,10])
#stock_prices([25,2,10,9])
#stock_prices([10,12,5,3,20,1,9,20])
#stock_prices([10,9,8,7,6])
#stock_prices([18,17,17,16,15])
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.