Maximum Subarray Sum(Kadane’s Algorithm) in Python

 Introduction

The subarrays sum problem is one of the most famous questions in Data Structures and Algorithms. Whether you’re preparing for a college exam or a Google interview, finding the maximum subarrays sum always comes up. And the best way to solve it? Kadane’s Algorithm.The challenge: given an array of integers, find the contiguous subarray that gives the largest possible sum. A brute-force approach checks every possible pair — that’s O(n²), which is too slow. Kadane’s Algorithm solves the maximum subarray sum problem in a single pass with O(n) time and O(1) space.In this guide, you’ll learn everything step by step — from understanding what subarrays sum means, to writing the Python code, running through a dry-run example, and acing the interview questions about it.

📌 Reference: This problem is listed as LeetCode Problem #53 – Maximum Subarray and is solved by millions of programmers worldwide. Also see the Maximum Subarray Problem on Wikipedia.

📋 Problem Statement

Given an array of integers (which can include negatives), find the contiguous subarray with the largest subarrays sum and return that sum.

Formal definition: A subarray is a contiguous part of the array. Your task is to identify which subarray yields the maximum possible subarrays sum.

Example 1

Input: [-2, 1, -3, 4, -1, 2, 1, -5, 4]
Output: 6
Reason: Subarray [4, -1, 2, 1] has the max subarrays sum = 6

Example 2

Input: [1, 2, 3, 4, 5]
Output: 15
Reason: All positive — total subarrays sum = 15 (take full array)

📥 Input / Output Format & Constraints

Input Format
  • First line: integer n (size of array)
  • Second line: n space-separated integers
Output Format
  • Print the maximum subarrays sum (single integer)
Constraints: 1 ≤ n ≤ 10⁵  |  –10⁴ ≤ arr[i] ≤ 10⁴  |  At least one element exists

🐢 Naive Approach (Brute Force)

The simplest idea: try every possible subarray, compute its subarrays sum, track the maximum. Two common brute-force versions exist:

  • O(n³) approach — Three nested loops: pick start, pick end, loop to sum
  • O(n²) approach — Two loops: pick start, extend end while accumulating subarrays sum
# O(n²) brute force — computes subarrays sum for every pair
def max_subarray_brute(arr):
    n = len(arr)
    max_sum = arr[0]
    for i in range(n):
        curr = 0
        for j in range(i, n):
            curr += arr[j]          
            max_sum = max(max_sum, curr)
    return max_sum
Problem: For n = 100,000 this runs ~10 billion operations. That’s TLE (Time Limit Exceeded) on every online judge.

Optimal Approach – Kadane’s Algorithm

Kadane’s Algorithm computes the maximum subarrays sum in a single pass using one brilliant observation:

At every element, ask: “Should I extend my current subarrays sum, or start a fresh subarray from here?” If the running total goes negative, restart — because a negative prefix can only hurt the subarrays sum going forward.

Only 2 variables are needed:

  • current_sum — the best subarrays sum ending at the current index
  • max_sum — the best subarrays sum seen anywhere in the array so far

At each step: current_sum = max(arr[i], current_sum + arr[i]). If the running subarrays sum is less than starting fresh, we restart. Then update max_sum if needed.

🔀 Algorithm Flowchart

Maximum Subarray Sum

📝 Pseudocode

FUNCTION kadane(arr):
    // Initialize both values to arr[0] for all-negative support
    current_sum ← arr[0]
    max_sum     ← arr[0]      // tracks best subarrays sum so far

    FOR i FROM 1 TO length(arr) - 1:
        current_sum ← MAX(arr[i], current_sum + arr[i])
        max_sum     ← MAX(max_sum, current_sum)

    RETURN max_sum             // maximum subarrays sum

🐍 Python Program

def kadane(arr):
    # Initialize to arr[0] — handles all-negative arrays correctly
    current_sum = arr[0]
    max_sum     = arr[0]   # best subarrays sum found so far

    for i in range(1, len(arr)):
        # Extend current subarray OR start a new one from arr[i]
        current_sum = max(arr[i], current_sum + arr[i])

        # Update maximum subarrays sum if we found a better one
        max_sum = max(max_sum, current_sum)

    return max_sum   # final answer: maximum subarrays sum


n   = int(input("Enter size of array: "))
arr = list(map(int, input("Enter elements: ").split()))

result = kadane(arr)
print("Maximum Subarrays Sum:", result)

🔍 Dry Run — Step by Step

Input: [-2, 1, -3, 4, -1, 2, 1, -5, 4]

Initial: current_sum = –2, max_sum = –2 (subarrays sum starts at first element)

Step Element curr + elem current_sum max_sum (subarrays sum)
1 1 –2+1 = –1 1 1
2 –3 1+(–3) = –2 –2 1
3 4 –2+4 = 2 4 4
4 –1 4+(–1) = 3 3 4
5 2 3+2 = 5 5 5
6 1 5+1 = 6 6 6 ✓
7 –5 6+(–5) = 1 1 6
8 4 1+4 = 5 5 6
Final Maximum Subarrays Sum = 6 — from subarray [4, –1, 2, 1]

💡 Code Explanation

  • current_sum = arr[0] — Start at the first element. Initializing to 0 would break all-negative subarrays sum cases.
  • max_sum = arr[0] — Tracks the overall best subarrays sum across the entire array.
  • max(arr[i], current_sum + arr[i]) — The core of Kadane’s: restart vs extend. If the current subarrays sum running total is dragging you down, cut it.
  • max(max_sum, current_sum) — After each step, update the global maximum subarrays sum if needed.
  • return max_sum — The final maximum subarrays sum after processing all elements.

📊 Time & Space Complexity

O(n)
Time Complexity

One pass through the array. Each element’s contribution to the subarrays sum is evaluated exactly once — no nested loops.

O(1)
Space Complexity

Only two variables used (current_sum, max_sum) regardless of input size. No extra arrays needed to track subarrays sum.

🧪 Test Cases

01

Mixed Numbers – Classic subarrays sum

[-2, 1, -3, 4, -1, 2, 1, -5, 4]

→ 6

02

All Positive – Full array is max subarrays sum

[1, 2, 3, 4, 5]

→ 15

03

All Negative – subarrays sum is least negative

[-3, -1, -4, -2]

→ -1

04

Single Element – subarrays sum = that element

[7]

→ 7

05

Zeros Included

[0, -1, 2, 0, 3, -2]

→ 5

06

Large Spike – single element dominates subarrays sum

[-5, -3, 100, -2, -1]

→ 100

⚠️ Edge Cases to Watch

  • All negatives: Don’t initialize max_sum to 0 — the subarrays sum answer would be wrong. Start with arr[0].
  • Single element: The loop never runs; subarrays sum = arr[0]. Works correctly.
  • Array with only zeros: Maximum subarrays sum = 0. The algorithm handles it cleanly.
  • Very large values: Python handles arbitrarily large integers — no overflow when computing subarrays sum.

🧠 Why Kadane’s Algorithm Works

Think of the subarrays sum like a stock portfolio. Each array element is a daily gain or loss. If your running total (subarrays sum so far) is negative, carrying it forward can only hurt you — so you cut losses and restart fresh.

Formally, Kadane’s computes the maximum subarrays sum ending at each index using this DP recurrence:

dp[i] = max(arr[i], dp[i-1] + arr[i])

Kadane’s is this DP recurrence optimized to O(1) space — no dp array stored, just two variables tracking the subarrays sum.

🎯 Common Interview Questions on Subarrays Sum

Q1. What is the time complexity of finding the maximum subarrays sum using Kadane’s?
O(n) — a single pass over the array. Each element contributes to the subarrays sum calculation exactly once.
Q2. Can Kadane’s handle all-negative arrays for subarrays sum?
Yes. Initialize both variables to arr[0], not 0. The algorithm returns the least negative element as the maximum subarrays sum.
Q3. How do you return the actual subarray alongside the sum?
Track start, end, and temp_start indices. Update temp_start when you restart the subarrays sum, and update start/end when you update max_sum.
Q4. What is the difference between Kadane’s and brute force for subarrays sum?
Brute force checks all O(n²) subarray pairs to find the maximum subarrays sum. Kadane’s uses a single greedy pass — O(n). For n=100,000, that’s billions of operations vs 100,000.
Q5. Is subarrays sum a Dynamic Programming problem?
Yes — dp[i] = max(arr[i], dp[i-1] + arr[i]) is the recurrence. Kadane’s Algorithm evaluates this in O(1) space by not storing the full dp array.

🌍 Real World Applications of Subarrays Sum

📈

Stock Profit Analysis

Maximum subarrays sum of daily gains/losses reveals the best buy-sell window.

🌡️

Temperature Streaks

Find the continuous period with the highest subarrays sum of temperature rise.

📡

Signal Processing

Detect the strongest subarrays sum burst in a time-series of signal amplitudes.

🎮

Game Scoring

Best consecutive subarrays sum scoring run for a player across match timeline.

🚫 Mistakes Beginners Make with Subarrays Sum

Mistake 1 — Initializing to 0: If the array is all negative, the subarrays sum answer would be wrongly 0. Always start both variables at arr[0].
Mistake 2 — Using sum() inside a loop: Recomputing subarrays sum from scratch each iteration makes it O(n²). Use a running total instead.
Mistake 3 — Forgetting the restart: Not using max(arr[i], current_sum + arr[i]) means negative subarrays sum values are never discarded.
Pro Tip: Always test your subarrays sum solution with an all-negative array like [-3, -1, -4, -2]. Expected output: -1 (not 0).

🏁 Conclusion

Kadane’s Algorithm is the definitive solution for the maximum subarrays sum problem. It’s elegant, fast, and once you understand the core insight — if the subarrays sum so far hurts you, let it go — you’ll never forget it.

This problem appears constantly in technical interviews, and explaining it confidently with a dry run, complexity analysis, and edge cases puts you miles ahead of other candidates.

Want to level up further? Try these related subarrays sum challenges:

  • Return the actual subarray that gives the maximum subarrays sum
  • Maximum subarray product (a twist on the subarrays sum idea)
  • Maximum circular subarrays sum

Frequently Asked Questions – Subarrays Sum & Kadane’s Algorithm

Kadane’s Algorithm finds the maximum subarrays sum of any contiguous subarray in O(n) time and O(1) space. It was proposed by Jay Kadane in 1984 and works by maintaining a running total that resets when it becomes negative.

The algorithm iterates through the array exactly once. At each position, it performs a constant number of operations to update the subarrays sum — two max() calls. Total work is proportional to n, making it O(n).
Yes! If the array is all negative, the maximum subarrays sum is the least negative element. Kadane’s handles this correctly by initializing to arr[0] instead of 0.

Brute force tries all O(n²) pairs to find the maximum subarrays sum. Kadane’s makes a single greedy decision at each step — extend or restart — reducing the problem to one O(n) pass.

Absolutely. Maximum subarrays sum (LeetCode #53) has appeared in interviews at Google, Amazon, Microsoft, and nearly every major tech company. It’s also a popular college exam question in India.

Python is ideal for interviews and learning due to its readability. C++ is preferred in competitive programming for speed. The subarrays sum algorithm logic is identical across all languages.

🎯 Featured Snippet – Quick Answer

What is the maximum subarrays sum problem?

Maximum subarrays sum is the largest sum of any contiguous subarray in a given array. Kadane’s Algorithm solves it in O(n) time by maintaining a running sum that resets when negative, updating the global maximum at each step.

 

 

Leave a Comment