cur = best subarray ending here; best = max over all cur.
At each element, either extend the current run or restart from this element, whichever is larger. Track the maximum cur ever seen.
Algorithm
cur = best = nums[0].- For each subsequent
x:cur = max(x, cur + x). best = max(best, cur).- Return
best.
- Time
- O(n)
- Space
- O(1)
class Solution: def maxSubArray(self, nums: list[int]) -> int: best = cur = nums[0] for x in nums[1:]: cur = max(x, cur + x) # extend the run, or restart here best = max(best, cur) return best