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].
source
share