-2
def max_subarr(arr)
  start_index, end_index = 0,
  (0...arr.length).inject([arr.first]) do |max_sub, i|
    (i...arr.length).each do |x|
      if max_sub.inject(:+) < arr[i..x].inject(:+)
        max_sub = arr[i..x]
        start_index, end_index = i, x
      end
    end
    max_sub
  end
  return [start_index, end_index]
end

max_subarr([98, -99, 198, -2, 950]) # => [2,4]

Could someone explain why we need the last max_sub when we have the max_sub = arr[i..x] in the nested loop? And, the function of inject([arr.first]) do |max_sub, i|

sawa
  • 165,429
  • 45
  • 277
  • 381
paulsus
  • 9
  • 3

1 Answers1

1

Sure: that block returns the new value for the memo object. That is, the next value of max_sub that is yielded to the block will be whatever that block returned the last time.

And the inject method of Enumerable is used to apply a binary operation or an arbitrary block, if provided, to an Enumerable.

For each element of the Enumerable, inject will apply the operation or pass the memo object and the current element to the block.

The memo object is either the parameter or, if absent, the first element of the block. It is typically accumulated via a block. Each yield to the block results in a new value of the memo. The last value of the memo object is then returned.

It's a structured and potentially functional way to reduce a data structure to a summary result.

Full docs here.

DigitalRoss
  • 143,651
  • 25
  • 248
  • 329
  • 1
    I prefer `each_with_object` over `inject` precisely because I don't need to remember to return the new value of memo :) – Sergio Tulentsev Jun 17 '16 at 18:48
  • @DigitalRoss so max_sub = arr[i..x] would return in the loop of (i...arr.length).each do |x|. And, the last max_sub would return the value bac k to (0...arr.length).inject([arr.first]) do |max_sub, i| ?? I was thinking the value would be assigned and return since max_sub = arr[i..x] – paulsus Jun 17 '16 at 20:02
  • @paulsus, at this point if you have further questions you should read the docs. Arguably, you should have done that before posting, lol. – DigitalRoss Jun 17 '16 at 21:30