http://www.perlmonks.org?node_id=570420

OverlordQ has asked for the wisdom of the Perl Monks concerning the following question:

Greetings monks!

A problem has come to my attention. Given an arbitrary sized array of integers in an arbitrary order, whats the sequence of consecutive integers that results in the largest sum.*

Given the array:
array = {3 2 8 9 -25 5 8 4 4 -3 5 3 -10}
The subset with the largest sum would be:
largestsubset = {5 8 4 4 -3 5 3}
This is what I came up with:
#!/usr/bin/perl use strict; use warnings; my @array = qw( 3 2 8 9 -25 5 8 4 4 -3 5 3 -10 ); my $length = scalar(@array); my $sidx; my $eidx; my $max = 0; my $start = 0; while($start < $length) { my $sum = $array[$start]; for(my $end = ($start + 1); $end < $length; $end++) { $sum += $array[$end]; if($sum > $max) { $sidx = $start; $eidx = $end; $max = $sum; } } $start++; }
Which gives you the nice and handy:
Start: 5 End: 11

Now of course that isn't pretty, but it works nicely for smaller sets. Only problem I could see is if the sets grow to an unreasonable size. Are there any more elegant ways of going at this?

One of my ideas was watching the value of sum and if it reached a negative value then break out of the inner loop.




* Yes, this is a homework question if you've guessed, but I already have a viable solution, and am just interested in more efficient algorithms, and not to mention we have to use Java.