# \[SOLUTION\] Maximum Sub-Array (#131)

**URL:** <https://www.ruby-forum.com/t/solution-maximum-sub-array-131/109483>\
**Category:** Ruby\
**Created:** [July 15, 2007, 5:41pm UTC](https://www.ruby-forum.com/t/solution-maximum-sub-array-131/109483 "2007-07-15T17:41:53Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![willbailey](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/w/e9c0ed/32.png) [@willbailey](https://www.ruby-forum.com/u/willbailey)\
**Post date:** [July 15, 2007, 5:41pm UTC](https://www.ruby-forum.com/t/solution-maximum-sub-array-131/109483/1 "2007-07-15T17:41:53Z")

</div>

Here is my solution. I extended Array to have a max\_slice method. It  
first  
checks if the array is all positives returning the array minus any zeros  
if  
so. Then it checks to see if the array is all negative or zero  
returning  
the max value if so. If both of these checks fail, it does an  
exhaustive  
search of the array storing the sum of each contiguous sub-array as the  
key  
in a hash with the value being the sub-array. I thought I was being a  
bit  
clever by joining the array with pluses and then calling eval to get the  
sum…but maybe this is not a good practice. Let me know what you  
think.

-Wb

class Array  
def max\_slice  
return self-[0] if select{|k|k\<0}.size==0  
return [max] if select{|k|k\>=0}.size==0  
p={}  
each\_with\_index do |o,i|  
i.upto(size-1) do |j|  
p[eval(slice(i…j).join("+"))] = slice(i…j)  
end  
end  
p.max[1]  
end  
end

puts [-1, 2, 5, -1, 3, -2, 1].max\_slice.inspect

# describe Array do

# it “should return the max slice” do

# input = [-1, 2, 5, -1, 3, -2, 1]

# input.max\_slice.should == [2, 5, -1, 3]

# end

# end
