Close Menu
    Code and Debug
    • Home
    • Our Courses
    • Blog
    • About Us
    • Contact Us
    Facebook X (Twitter) Instagram YouTube WhatsApp
    • Home
    • Our Courses
    • Blog
    • About Us
    • Contact Us
    Facebook Instagram YouTube LinkedIn WhatsApp
    Code and Debug – BlogCode and Debug – Blog
    Code and Debug – BlogCode and Debug – Blog
    Home»Data Structures & Algorithms»Maximum Subarray | Kadane’s Algorithm | From Brute Force to Optimal
    Data Structures & Algorithms

    Maximum Subarray | Kadane’s Algorithm | From Brute Force to Optimal

    codeanddebugBy codeanddebug26 June 2025No Comments3 Mins Read
    Share Facebook Twitter Pinterest LinkedIn Tumblr Reddit Telegram Email
    Featured image of question of kadanes algorithm
    Share
    Facebook Twitter LinkedIn Pinterest Email

    Explore the Maximum Subarray problem with a brute-force triple loop, a quadratic improvement, and the optimal Kadane’s Algorithm, all with intuition, fully-commented Python, dry runs, and complexity analysis.

    Here’s the [Problem Link] to begin with.

    Contents:
     [show]
    • 📚 Common Example for All Sections
    • 1️⃣ Brute Force – Triple Loop
      • 1.1 Intuition & Approach
      • 1.2 Python Code (with comments)
      • 1.3 Dry Run (first five iterations)
      • 1.4 Complexity
    • 2️⃣ Better Brute – Double Loop
      • 2.1 Intuition & Approach
      • 2.2 Python Code (with comments)
      • 2.3 Dry Run (first start index i = 0)
      • 2.4 Complexity
    • 3️⃣ Optimal – Kadane’s Algorithm
      • 3.1 Core Insight
      • 3.2 Algorithm Steps
      • 3.3 Python Code (with comments)
      • 3.4 Dry Run on Example Array
      • 3.5 Complexity
    • ✨ Summary Table

    Find the contiguous slice of an array whose elements add up to the largest possible sum.

    We’ll walk through three distinct solutions, each in its own self-contained section so you can master them one at a time:

    SectionTimeSpaceCore idea
    1. Brute Force (Triple Loop)O(n³)O(1)Check every subarray, add fresh each time
    2. Better Brute (Double Loop)O(n²)O(1)Carry a running sum inside the inner loop
    3. Optimal – KadaneO(n)O(1)Drop negative baggage as you scan

    Common Example for All Sections

    nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
    The best subarray is [4, -1, 2, 1] with sum 6.


    1. Brute Force – Triple Loop

    1.1 Intuition & Approach

    1. Pick every start index i.
    2. Pick every end index j ≥ i.
    3. Add every element from i to j in a third loop.
    4. Keep the maximum sum seen.

    1.2 Python Code (with comments)

    class Solution:
        def maxSubArray(self, nums: List[int]) -> int:
            maxi = float("-inf")            # global best
            n = len(nums)
            for i in range(n):              # start index
                for j in range(i, n):       # end index
                    cur_sum = 0
                    for k in range(i, j + 1):  # walk i…j
                        cur_sum += nums[k]
                    maxi = max(maxi, cur_sum)  # update best
            return maxi

    1.3 Dry Run (first five iterations)

    ijcur_summaxi
    00-2-2
    01-1-1
    02-4-1
    0300
    04-10

    Eventually maxi becomes 6.

    1.4 Complexity

    • Time O(n³) – three nested loops
    • Space O(1) – only scalars

    Good for teaching but impractical beyond tiny arrays.


    2. Better Brute – Double Loop

    2.1 Intuition & Approach

    Reuse the running sum s as the end index j expands; no need to recompute from scratch.

    2.2 Python Code (with comments)

    class Solution:
        def maxSubArray(self, nums: List[int]) -> int:
            maxi = float("-inf")
            n = len(nums)
            for i in range(n):          # start index
                s = 0
                for j in range(i, n):   # extend to the right
                    s += nums[j]        # add current element
                    maxi = max(maxi, s) # update best
            return maxi

    2.3 Dry Run (first start index i = 0)

    js after += nums[j]maxi
    0-2-2
    1-1-1
    2-4-1
    300
    4-10

    2.4 Complexity

    • Time O(n²) – one loop dropped
    • Space O(1)

    A huge speed-up over triple loops, but still slow for n ≈ 10⁵.


    3. Optimal – Kadane’s Algorithm

    3.1 Core Insight

    Maintain the best prefix sum ending at the current index.
    If that prefix becomes negative, starting fresh at the next index can only help.

    3.2 Algorithm Steps

    1. Let curSum = 0, maxi = -∞.
    2. For each element num in nums
      • curSum += num
      • maxi = max(maxi, curSum)
      • If curSum < 0, reset curSum = 0 (drop negative prefix).
    3. maxi now holds the answer.

    3.3 Python Code (with comments)

    class Solution:
        def maxSubArray(self, nums: List[int]) -> int:
            maxi = float("-inf")   # best seen so far
            curSum = 0             # sum of current window
    
            for num in nums:
                curSum += num          # extend window
                maxi = max(maxi, curSum)
    
                if curSum < 0:         # negative drag – cut here
                    curSum = 0
    
            return maxi

    3.4 Dry Run on Example Array

    IndexnumcurSum after +=maxiAction
    0-2-2-2reset (curSum = 0)
    1111keep
    2-3-21reset
    3444keep
    4-134keep
    5255keep
    6166keep
    7-516keep
    8456done

    3.5 Complexity

    • Time O(n) – one pass
    • Space O(1) – two scalars

    Kadane’s Algorithm is optimal for this problem.


    Summary Table

    SolutionTimeSpaceWhen to use
    Triple LoopO(n³)O(1)Teaching brute force
    Double LoopO(n²)O(1)Small n (≲ 1 000)
    KadaneO(n)O(1)Any real input (LeetCode, interviews)

    Remember the focus phrase—Maximum Subarray | Kadane’s Algorithm—and reach for Kadane to ace this classic interview favorite.

    Join our Advance DSA COURSE

    For any changes to the article, kindly email at code@codeanddebug.in or contact us at +91-9712928220.

    Array Easy
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Previous ArticleFind the City With the Smallest Number of Neighbors at a Threshold Distance | Floyd Warshall vs. Dijkstra
    codeanddebug
    • Website

    Related Posts

    Data Structures & Algorithms

    Find the City With the Smallest Number of Neighbors at a Threshold Distance | Floyd Warshall vs. Dijkstra

    26 June 2025
    Data Structures & Algorithms

    Floyd Warshall vs. Multi-Source Dijkstra | Two Ways to Solve All-Pairs Shortest Paths

    26 June 2025
    Data Structures & Algorithms

    Bellman Ford Algorithm | Distance from the Source Explained Step-by-Step

    26 June 2025
    Add A Comment
    Leave A Reply Cancel Reply

    Categories
    • Data Structures & Algorithms (67)
      • Beginner (30)
      • Expert (17)
      • Intermediate (20)
    • Uncategorised (1)
    Recent Posts

    Maximum Subarray | Kadane’s Algorithm | From Brute Force to Optimal

    26 June 2025

    Find the City With the Smallest Number of Neighbors at a Threshold Distance | Floyd Warshall vs. Dijkstra

    26 June 2025

    Floyd Warshall vs. Multi-Source Dijkstra | Two Ways to Solve All-Pairs Shortest Paths

    26 June 2025

    Bellman Ford Algorithm | Distance from the Source Explained Step-by-Step

    26 June 2025

    Number of Ways to Arrive at Destination | Leetcode 1976 | Simple Dijkstra + Path-Counting Guide in Python

    26 June 2025
    Facebook Instagram YouTube LinkedIn WhatsApp
    © 2025 Code and Debug. All rights reserved.

    Type above and press Enter to search. Press Esc to cancel.