in reply to Re: Largest Sum of Consecutive Integers
in thread Largest Sum of Consecutive Integers

Ah, just a matter of finding the right abstraction / realization that allows you to see why each algorithm always finds the right answer. For this one, a simple two-part realization does it:

(----- the full list -------) [-- max sum --] <neg><pos><- plus ->

If a subrange has the maximum sum, then splitting that range into two new subranges will always give you two ranges that each have non-negative sums (otherwise the other new subrange would be an even better choice). In particular, if "<pos>" has a negative sum, then "[-- max sum --]" does not have the maximum sum.

Conversely, any non-empty subrange directly to the left ("<neg>") of the max-sum subrange will have a negative sum (else adding that in would give a better sum).

- tye        

Replies are listed 'Best First'.
Re^3: Largest Sum of Consecutive Integers (abstraction)
by johnnywang (Priest) on Aug 31, 2006 at 17:53 UTC
    Another observation is that you can always add the consecutive postive or negative numbers together, so you only need to deal with the case when the sequence is alternating, +-+-+-+-...+. That may simplify the logic. But tilly's solution is certainly elegant, the only "drawback" is that it's not symmetric, would be more beautiful if it went from both ends.