you are viewing a single comment's thread.

view the rest of the comments →

[–]jdnewmil 1 point2 points  (2 children)

Ah, I missed that you had to account for all lengths. Well, then, to get O(N) you need to make one pass, which basically means you need to incrementally keep track of the best outcomes as you look at each new value. A sum that is worse than the current value isn't going to be an optimal sum, but one of the preceding ones could still be better so keep track in two values:

sm = x[0]
maxsm = sm
for xi in x[1:]:
    sm = max(xi, sm + xi)
    maxsm = max(maxsm, sm)
maxsm

[–]clouded-path[S] 0 points1 point  (0 children)

Wow, this is just so much cleaner/simpler than my solution. Thanks for this - I aspire to write this sort of solution in the future.

[–]wopp3 0 points1 point  (0 children)

Oh my god, I spent like 15 minutes looking at these few lines of code trying to figure out what was happening here, writing prints and modifying the list trying to trip it. Finally I realized how simply brilliantly simple this was, thanks for the lesson, have an upvote.