From: "Eric I." Date: 2007-07-15T23:50:00+09:00 Subject: Re: Maximum Sub-Array (#131) [SOLUTION] I went for the all-in-one line solution (not including the method definition boilerplate), with no consideration for the computational or memory cost. Here are two versons, the first does not require the 'enumerator' library, the second does and is slightly shorter as a result. Both will favor shorter solutions over longer solutions if they have the same sum. In both cases the code generates every possible sub-array and sorts them by two factors: 1) sum of elements ascending, and 2) size of sub- array descending. Finally it chooses the solution at the end of this sorted list. In the first solution, it generates every sub-array by using all possible combinations of starting and ending indices. def max_sub_array(a) (0...a.size).inject([]) { |c, s| c + (s...a.size).map { |e| a.slice(s..e) } }.sort_by { |b| [b.inject { |s, e| s + e }, - b.size] }.last end In the second solution, it generates every sub-array by sequencing through all possible sub-array lengths (1..size) and then calling enum_cons. If you're not familiar with enum_cons, it takes a size as a parameter and returns an Enumerable for every sub-array of that size (e.g., [1, 2, 3, 4].enum_cons(2) would provide an Enumerable that would encode the sequence [1, 2], [2, 3], and [3, 4]). def max_sub_array2(a) (1..a.size).inject([]) { |l, s| l + a.enum_cons(s).to_a }.sort_by { | b| [b.inject { |s, e| s + e }, -b.size] }.last end Eric ==== Are you interested in on-site Ruby training that uses well-designed, real-world, hands-on exercises? http://LearnRuby.com