Maximum Subarray (Kadane) visualization

Best sum of a contiguous subarray: extend the current run or restart at the current element.

cur = max(A[i], cur + A[i]) — if the running sum so far is negative, it only hurts, so start fresh. Track the best cur seen.

Edge case: when every number is negative, the answer is the largest single element (not 0). Initialising best with A[0] instead of 0 handles this.

Complexity

Time: best O(n), average O(n), worst O(n). Space: O(1). Difficulty: Beginner.

Pseudocode

procedure maxSubarray(A):
  cur ← A[0]; best ← A[0]
  for i ← 1 to n−1:
    cur ← max(A[i], cur + A[i])        // extend or restart
    best ← max(best, cur)
  return best

More dynamic programming algorithms