Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??

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.

In reply to Largest Sum of Consecutive Integers by OverlordQ

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others cooling their heels in the Monastery: (4)
As of 2024-04-20 00:27 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found