At each element decide: extend the running subarray, or start fresh here. The best sum ever seen is the answer.
Find the contiguous subarray with the largest sum in a single pass. The whole algorithm is one question asked at every element: is the run I have been carrying still worth carrying, or is this element better off on its own? `current` is the best sum of any subarray ENDING at i; `best` is the best sum seen anywhere so far.
`current` answers "what is the best subarray that ends exactly here?". `best` answers "what is the best subarray I have seen anywhere?". Both start at nums[0], because with one element there is only one subarray. `current` is recomputed every step; `best` only ever moves up.
At index i there are only two candidates for the best subarray ending at i: the previous run stretched by one (`current + nums[i]`), or nums[i] standing alone. Take the larger. If nums[i] alone wins, the prefix was a net drag. Dropping it can only help, so the window collapses onto i and starts again from there.
The run restarts twice: at index 1 (the -2 prefix is dead weight) and at index 3 (the -2 running total is worse than 4 alone). From index 3 the window only grows, peaking at 6 across [3..6], and nothing later beats it.
Every subarray ends somewhere. If you know the best subarray ending at each index, the answer is the largest of those n values, and that is what `best` collects. And the best subarray ending at i either includes i-1 or it does not, which is exactly the two candidates compared. Seeding with nums[0] rather than 0 is what makes an all-negative array return its largest element instead of an empty-subarray 0.
One pass, with one comparison and one max per element, so O(n) time. Only two running integers are kept (plus the window bounds if you want the subarray itself), so O(1) extra space.
Track the window bounds (start moves to i on a restart, and a new best snapshots the window) and you get the subarray itself as well as its sum. The same "carry the running optimum, reset when the prefix stops helping" shape solves best time to buy and sell stock, maximum product subarray (keep a running min too, because a negative can flip), and the circular maximum subarray via total − minimum subarray.