Perl: the Markov chain saw PerlMonks

### Re: Largest Sum of Consecutive Integers (ends)

by tye (Sage)
 on Aug 30, 2006 at 18:06 UTC ( #570444=note: print w/replies, xml ) Need Help??

in reply to Largest Sum of Consecutive Integers

The sum of a contiguous subset is the total sum minus the sum of the left-side items that are left out and minus the sum of the right-side items that are left out. So instead of looking at O(N*N) combinations you can look at O(N) left-side possibilities and O(N) right-side possibilities and get the best answer. If an end-sum is not negative, then there is no benefit in omitting those items so only consider removing an end-run of items if it has a negative sum and the lowest sum of the end-runs.

But then you've got to deal with the special cases when this doesn't work. They aren't terribly tough to figure out but they certainly complicate the code. The trick is realizing these cases, but you'll probably hit them if you consider lists where most (or all) of the numbers are negative.

Update: But I haven't proven this to be correct, so there may be cases I haven't considered.

- tye

• Comment on Re: Largest Sum of Consecutive Integers (ends)

Replies are listed 'Best First'.
Re^2: Largest Sum of Consecutive Integers (means)
by tye (Sage) on Aug 30, 2006 at 19:09 UTC

A "fun" challenge would be to come up with a dataset where my above method won't work. I think such exist, but I don't see clearly how to construct one (probably a lot of alternating positive and negative numbers).

Dealing with the sum of left- and right-side end-runs certainly makes the problem easier to think about. I think I've got a much simpler-to-implement algorithm that will work on any set now.

I'd construct the list of left-side end-run sums and the list of right-side end-run sums and track the "most negative so far" as you build it. Then you can just iterate one list and look up in the other list and select the maximum sum in O(N).

If it weren't homework and/or I wasn't busy doing stuff that I get paid for, then I'd probably write up the code to do that. :)

- tye

I just gotta figure out what the heck you just said ;)

Create A New User
Node Status?
node history
Node Type: note [id://570444]
help
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (4)
As of 2018-07-19 10:20 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
It has been suggested to rename Perl 6 in order to boost its marketing potential. Which name would you prefer?

Results (406 votes). Check out past polls.

Notices?