@esha_d you walk the n-element array once for the collect call. And
within each collect call you walk the array via k.max. That is O(n^2)
if my vague recollection of uni serves me. Each call to k.max requires
a walk of the array, unless the interpreter used caches k.max after the
first walk.

The way I see this working (please check me):
k.each_with_index creates an enumerator so no looping there. But collect
walks the array (with the embedded k.max). Then compact must walk the
result of collect to strip out the nil's.

Given we know k doesn't change over the collect loop we can pull the
k.max out.
k_max = k.max;
Then you loop over a k.size array once for the initial k.max, once for
the collect, and a last time for the compact.

It is possible to write the loop to walk the k array once with an each.
And loop over the result set once to strip out the indexes.

a = [9, 9, 6, 0, 1, 4, 5, 6, 9, 1, 9]
b = []
a.each_with_index do |e,i|
  cur_max = (b.empty?) ? e : b[0][1]
  if e > cur_max
    b = [[i,e]]
  elsif e == cur_max
    b.push [i,e]
  end
end
p b.collect {|e| e[0] }

Algorithmically both approaches are O(n), other than the k.max thing.
However, it is clear that one is 3n versus n+m (where m is the result
set size).

-LLeo

-- 
Posted via http://www.ruby-forum.com/.