DSA
    intermediate

    Kadane's Algorithm

    Kadane's Algorithm

    Find the maximum sum contiguous subarray in O(n) time. The quintessential dynamic programming problem that every FAANG interview expects you to know.

    ⏱ O(n)
    💾 O(1)
    Ready
    -2
    1
    -3
    4
    -1
    2
    1
    -5
    4
    In current subarray
    Current index
    Current Sum
    -2
    Max Sum
    -2

    Initialize: currentSum = maxSum = arr[0] = -2

    50%
    Live Variables
    currentSum-2
    maxSum-2

    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