DSA
    intermediate

    Kadane's Algorithm

    Software Engineer path · lesson 37 of 99
    time O(n)
    space O(1)

    Up to 14 whole numbers from -99 to 99.

    Try:
    cur -2-2011-3243-142516-5748i
    Current runRestart hereBest run

    Start with cur = best = a[0] = -2.

    Code (running line highlighted)
    1. 1cur = best = a[0]
    2. 2for i in 1 .. n-1:
    3. 3 cur = max(a[i], cur + a[i]) # extend or restart
    4. 4 best = max(best, cur)
    5. 5return best
    Extend/restart decisions
    0 / 8
    Invariant: cur = best sum of a subarray ending exactly at index 0; best = best seen anywhere in a[0..0].

    Tap any element in the diagram to inspect its state at this step.

    1 / 14

    Keys: ← → step, Space play/pause. Predict mode pauses before key steps and asks what happens next.

    Kadane in one pass

    Sequence

    Order the steps for the maximum subarray sum.

    Tap a piece, then tap where it goes — or drag it. Tap the tray to take one back.

    1. 1Drop a step here
    2. 2Drop a step here
    3. 3Drop a step here
    4. 4Drop a step here
    5. 5Drop a step here
    5 pieces left to place

    Test your knowledge

    20 questions
    Question 1 of 20
    Score: 0

    What decision does Kadane's algorithm make at each element?

    The short version

    Imagine you're tracking your stock portfolio. At each day, you decide: 'Should I keep adding to my current streak, or cut losses and start fresh?' Kadane's makes this decision at every step.

    In more depth

    The Core Insight

    At each position, we have two choices:

    1.Extend: Add current element to existing subarray
    2.Restart: Start a new subarray from current element

    We choose whichever gives a larger sum.

    Recurrence:

    currentSum = max(arr[i], currentSum + arr[i])
    maxSum = max(maxSum, currentSum)

    Why It Works

    If the running sum becomes negative, it can only hurt future subarrays. Better to start fresh!

    When to reach for this

    • Find maximum/minimum contiguous subarray
    • Optimization over all subarrays
    • Keywords: 'contiguous', 'subarray', 'maximum sum'

    Interview Questions

    Amazon
    Microsoft
    Bloomberg
    Uber
    Amazon
    LinkedIn
    Facebook
    Uber
    Netflix

    Love this visualization?

    Sign up to track your progress, earn achievements, use the AI assistant, and access your personal learning dashboard.

    100% free • No credit card required