Continue learning
Practice related DSA questions in the same topic.
Return the largest sum of a nonempty contiguous segment.
Return the largest sum of a nonempty contiguous segment.
def solve(values, target): ending = values[0] best = ending i = 1 while (i < len(values)): ending = max(values[i], (ending + values[i])) best = max(best, ending) i = (i + 1) return bestChoose between a fresh start and extending the segment.
Choose between a fresh start and extending the segment.
Carry yesterday’s savings forward only when they improve today’s balance.
The best segment ending here either starts here or extends the previous best ending.
O(n) time · O(1) auxiliary space
Worked example · {"values":[-3,4,-1,5,-8],"target":0} ⇒ 8
Edge case 1 · {"values":[-7,-2],"target":0} ⇒ -2
Edge case 2 · {"values":[0],"target":0} ⇒ 0
Initializing the answer to zero incorrectly allows an empty segment on all-negative input.
How would you recover both endpoints?