Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

Re^2: Largest Sum of Consecutive Integers (abstraction)

by tye (Sage)
on Aug 31, 2006 at 17:00 UTC ( [id://570640]=note: print w/replies, xml ) Need Help??


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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://570640]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others pondering the Monastery: (3)
As of 2024-04-26 00:19 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found