Given an integer array nums, find the subarray with the largest sum, and return its sum.
nums = [-2,1,-3,4,-1,2,1,-5,4]6A negative prefix can never improve a future subarray — it only drags the sum down. When currSum < 0, reset to 0 (start fresh from next element). At each index, currSum equals the maximum subarray sum ending here. maxSum tracks the global best across all positions.
Checking every subarray is O(n²). And you cannot simply skip negatives, because the best run here contains a −1.
At each index, either extend the current run, or start a fresh run from here. If the running sum has gone negative, it only hurts what comes next, so drop it.
Remember Kadane's rule: extend the run, or restart when the run is negative. Keep the best sum separately from the current run.
Run the animation above on your own input, or watch the 1:16 video explanation of Maximum Subarray with a dry run and Java code.