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


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 ;)