Skip to content
intermediate

Kadane's scan for the best subarray

Complete the one-pass maximum subarray sum — the running sum that either extends or restarts at every element.

/**
 * Returns the largest sum of any non-empty contiguous subarray.
 * The input has at least one element.
 */
export function maxSubarraySum(nums: number[]): number {
  let ____ = -Infinity
  let _______ = -Infinity

  for (const _____ of nums) {
    // Extend the run, or restart here — whichever wins.
    current = Math.max(current + value, value)
    best = Math.max(best, current)
  }

  return best
}
0/3 filled tab moves · Ctrl+↵ submits · Ctrl+Shift+↵ runsstarter code