Ruby - find subarray indexes

I am having trouble finding a way to extract subarray indices.

Problem : Find the submachine with the maximum value from one source array.

My solution : finds the correct array, but returns the values ​​in the array.

I need : index of the index of the beginning and end of the maximum subarray; Example [2, 4].

My code is:

def max_subarr(arr)
  (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]
      end
    end
    max_sub
  end
end

Any help is greatly appreciated - and please include a brief explanation of what I'm doing wrong. I know that max_sub returns values arr[i..x], but for my life I can’t just return the values ​​of the index max_sub[i]and max_sub[x].

+4
source share
1 answer

:

indexes_arr = [2, 4]
range = Range.new(*indexes_arr)
arr[range]

:

, , .

:

def max_subarr(arr)
 start_index, end_index = 0, 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]
0

Source: https://habr.com/ru/post/1526576/


All Articles