Function Assignment 33 β€” Find the Contiguous Subarray with the Largest Sum (Kadane's Algorithm)
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Find the Contiguous Subarray with the Largest Sum (Kadane's Algorithm)

πŸ“‘ On this page:
  • What the maximum-sum subarray problem is
  • Kadane's algorithm β€” the O(n) insight
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
πŸ“š In this program, you will learn:
  • What a contiguous subarray is β€” and why the naive approach is too slow
  • Kadane's algorithm β€” the O(n) insight that solves this in a single pass
  • Why "reset when the running sum goes negative" is the correct local decision
  • How to handle all-negative arrays correctly
  • How to extend Kadane's algorithm to find the actual subarray bounds

What the maximum-sum subarray problem is

Given an array of integers, find the contiguous subarray (a slice of consecutive elements) whose sum is the largest. A "subarray" must be contiguous β€” you can't skip elements. So for [1, 2, 3, 4, 5], valid subarrays include [1], [1, 2], [2, 3, 4], [1, 2, 3, 4, 5], and so on. The maximum sum subarray is the entire array, sum 15. For [-2, 1, -3, 4, -1, 2, 1, -5, 4], the maximum sum subarray is [4, -1, 2, 1], sum 6.

This is one of the most famous algorithmic problems in computer science, and it appears in dozens of interview questions and practical applications. Stock trading (maximum profit from a series of daily changes), signal processing (find the strongest contiguous burst), and image analysis (find the brightest region) all reduce to variants of this problem. It's also the textbook example for teaching dynamic programming and the "local choice β†’ global optimum" reasoning.

The naive approach β€” check every possible subarray β€” is O(nΒ³) if you sum from scratch each time, or O(nΒ²) if you precompute prefix sums. For an array of 10,000 elements, that's 100 million to 10ΒΉΒ² operations. Way too slow for real work. Kadane's algorithm solves this in O(n) β€” a single pass, two variables, no extra space. It's one of those rare algorithms where the fast solution is also the simpler one, once you see the insight.

The insight: as you scan left to right, keep the sum of "the best subarray ending at the current position." If that running sum ever goes negative, it's dragging you down β€” any future subarray that includes it would be better off starting fresh. So reset the running sum to 0 and start again at the next element. Meanwhile, track the maximum value the running sum has ever reached. That maximum is your answer. One pass, done.

πŸ’‘ In one line: current = max(arr[i], current + arr[i]); best = max(best, current); for each i. Initialize both to arr[0]. The answer is best.

An array with the maximum-sum subarray highlighted, showing the values summed to get the maximum.

Kadane's algorithm β€” the O(n) insight

Here's the whole algorithm:

current = arr[0]
best    = arr[0]

for i = 1 to n-1:
    current = max(arr[i], current + arr[i])
    best    = max(best, current)

return best
                                

Two variables, two updates per iteration, one pass. The magic is in what current represents: it's the sum of the maximum-sum subarray ending at index i. That's a restricted version of the problem, and it's what makes the DP work. At each step, the best subarray ending at i is either:

  • Just arr[i] (start fresh).
  • arr[i] plus the best subarray ending at i-1 (extend).

Those are the only two possibilities for a contiguous subarray ending at i. And we choose the better of them. The recurrence current = max(arr[i], current + arr[i]) expresses exactly that decision.

Let's trace it for [-2, 1, -3, 4, -1, 2, 1, -5, 4] (the classic LeetCode example):

i arr[i] current best Reason
0-2-2-2Initial values
1111max(1, -2+1=-1) = 1 (fresh start)
2-3-21max(-3, 1-3=-2) = -2
3444max(4, -2+4=2) = 4 (fresh start)
4-134max(-1, 4-1=3) = 3
5255max(2, 3+2=5) = 5
6166max(1, 5+1=6) = 6
7-516max(-5, 6-5=1) = 1
8456max(4, 1+4=5) = 5

The maximum is 6, achieved by the subarray [4, -1, 2, 1] (indices 3 to 6). The trace shows the two key decisions:

  • At i=1 (arr=1): the running sum was -2 (bad), so we start fresh at 1.
  • At i=3 (arr=4): the running sum was -2 (bad), so we start fresh at 4.

After i=3, the running sum never goes negative again, so we just keep extending: 4 β†’ 3 β†’ 5 β†’ 6. The final answer is the max over all values of current.

🎯 The core insight: a negative running sum is always a liability β€” any subarray that includes it would be better off starting after it. So reset to 0 (i.e., start fresh at the next element). This local decision is globally optimal, and it's what makes Kadane's algorithm work.

Complete C Program

Program: find the maximum sum subarray

#include <stdio.h>

/* Function prototype */
long long maxSubarraySum(const int arr[], int n);

int main(void) {
    int arr[100];
    int n;

    printf("How many elements? ");
    if (scanf("%d", &n) != 1 || n <= 0 || n > 100) {
        printf("Please enter a valid count between 1 and 100.\n");
        return 1;
    }

    printf("Enter %d integers: ", n);
    for (int i = 0; i < n; i++) {
        if (scanf("%d", &arr[i]) != 1) return 1;
    }

    printf("Maximum sum subarray: %lld\n", maxSubarraySum(arr, n));

    return 0;
}

/* Kadane's algorithm */
long long maxSubarraySum(const int arr[], int n) {
    long long current = arr[0];
    long long best = arr[0];

    for (int i = 1; i < n; i++) {
        long long extended = current + arr[i];
        if (arr[i] > extended) current = arr[i];
        else current = extended;

        if (current > best) best = current;
    }

    return best;
}
                                    

And a version that also reports the start and end indices of the maximum-sum subarray:

Variant: report the subarray bounds

#include <stdio.h>

long long maxSubarrayWithBounds(const int arr[], int n,
                                int *outStart, int *outEnd) {
    long long current = arr[0];
    long long best = arr[0];
    int curStart = 0;
    int bestStart = 0, bestEnd = 0;

    for (int i = 1; i < n; i++) {
        if (current + arr[i] < arr[i]) {
            current = arr[i];
            curStart = i;
        } else {
            current += arr[i];
        }
        if (current > best) {
            best = current;
            bestStart = curStart;
            bestEnd = i;
        }
    }

    *outStart = bestStart;
    *outEnd = bestEnd;
    return best;
}

int main(void) {
    int arr[] = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
    int n = sizeof(arr) / sizeof(arr[0]);
    int s, e;
    long long sum = maxSubarrayWithBounds(arr, n, &s, &e);

    printf("Max sum: %lld\n", sum);
    printf("Subarray [%d..%d]: ", s, e);
    for (int i = s; i <= e; i++) printf("%d ", arr[i]);
    printf("\n");
    return 0;
}
                                

The extra tracking is minimal β€” one variable curStart to remember where the current run started, and two to remember the best. When the running sum can't be improved by extending, we start fresh at i and update curStart = i. Whenever a new best is found, we snapshot the current run's bounds. Result: not just the sum but the exact indices.

And a version that shows each step of the algorithm:

Variant: verbose trace

#include <stdio.h>

long long maxSubarrayVerbose(const int arr[], int n) {
    long long current = arr[0], best = arr[0];
    printf("i=0, arr[0]=%d: current=%lld, best=%lld\n",
           arr[0], current, best);

    for (int i = 1; i < n; i++) {
        long long extended = current + arr[i];
        if (arr[i] > extended) current = arr[i];
        else current = extended;

        if (current > best) best = current;

        printf("i=%d, arr[%d]=%d: extended=%lld, fresh=%d β†’ current=%lld, best=%lld\n",
               i, i, arr[i], extended, arr[i], current, best);
    }
    return best;
}

int main(void) {
    int arr[] = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
    int n = 9;
    printf("\nFinal answer: %lld\n", maxSubarrayVerbose(arr, n));
    return 0;
}
                                

Running this shows every decision: at each step, whether we extend (extended > fresh) or start fresh. It's the clearest way to internalize the algorithm β€” you can see the running sum dip into negatives, get reset, and grow back up.

Program Output

A typical run with the classic example:

How many elements? 9
Enter 9 integers: -2 1 -3 4 -1 2 1 -5 4
Maximum sum subarray: 6
                                

The maximum-sum subarray is [4, -1, 2, 1] (indices 3 through 6), sum 6. This is the well-known answer for the LeetCode #53 example.

With all positive numbers:

How many elements? 5
Enter 5 integers: 1 2 3 4 5
Maximum sum subarray: 15
                                

When everything is positive, the maximum-sum subarray is the entire array. Sum = 1+2+3+4+5 = 15.

With all negative numbers:

How many elements? 4
Enter 4 integers: -3 -1 -4 -2
Maximum sum subarray: -1
                                

When all values are negative, the best you can do is the single largest element (least negative). Here, -1 is the max. This is why initializing current = arr[0] and best = arr[0] is critical β€” initializing to 0 would incorrectly return 0 for all-negative arrays (the empty subarray, which is not a valid answer).

A single element:

How many elements? 1
Enter 1 integers: 42
Maximum sum subarray: 42
                                

The loop doesn't execute, and the function returns arr[0] = 42, which is correct β€” the only subarray is the single element.

And the bounds-reporting variant:

Max sum: 6
Subarray [3..6]: 4 -1 2 1
                                

Not just "the max is 6" but "the max is 6, from indices 3 to 6, values 4, -1, 2, 1." That's the version most real applications want.

And the verbose trace:

i=0, arr[0]=-2: current=-2, best=-2
i=1, arr[1]=1: extended=-1, fresh=1 β†’ current=1, best=1
i=2, arr[2]=-3: extended=-2, fresh=-3 β†’ current=-2, best=1
i=3, arr[3]=4: extended=2, fresh=4 β†’ current=4, best=4
i=4, arr[4]=-1: extended=3, fresh=-1 β†’ current=3, best=4
i=5, arr[5]=2: extended=5, fresh=2 β†’ current=5, best=5
i=6, arr[6]=1: extended=6, fresh=1 β†’ current=6, best=6
i=7, arr[7]=-5: extended=1, fresh=-5 β†’ current=1, best=6
i=8, arr[8]=4: extended=5, fresh=4 β†’ current=5, best=6

Final answer: 6
                                

Every decision is visible. At i=1 and i=3, the extended sum is worse than starting fresh, so we reset. At i=6, we reach the peak of 6. After that, the running sum drops but the best is already recorded. The final answer is 6.

Step-by-Step Explanation

Let's understand the algorithm deeply, then walk through the code.

1. The recurrence

The best subarray ending at index i is max(arr[i], best_ending_at(i-1) + arr[i]). Two choices: start fresh at arr[i], or extend the previous best. Whichever gives a larger sum wins. This is the local decision β€” and it turns out to be globally correct, in the sense that the global maximum is the maximum over all local bests.

2. Why it works

Suppose the maximum-sum subarray ends at index k. Then its sum is exactly best_ending_at(k) β€” the best subarray ending at k. And our algorithm computes that correctly, by induction:

  • Base case: best_ending_at(0) = arr[0]. Trivially true (only one subarray ends at index 0).
  • Inductive step: the best subarray ending at k either includes arr[k-1] or doesn't. If it does, it must be the best ending at k-1 extended by arr[k]. If not, it's just arr[k]. So best_ending_at(k) = max(arr[k], best_ending_at(k-1) + arr[k]). This is our recurrence.

By induction, our recurrence computes the correct value at each step. The global maximum is then the maximum over all best_ending_at(k), which is exactly what best = max(best, current) tracks.

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

Already traced in the table above. Key moments:

  • After i=1, current = 1 (fresh start at 1, because extending -2 would be -1, worse than 1).
  • After i=3, current = 4 (fresh start, because extending -2 would be 2, worse than 4).
  • After i=6, current = 6 (the peak β€” extending 5 with 1 gives 6).
  • best tracks 6 from i=6 onward.

4. Why initialize to arr[0] and not 0

For all-negative arrays, initializing to 0 would give a wrong answer. For [-3, -1, -4, -2], the maximum-sum subarray is [-1] with sum -1. If best started at 0, we'd never update it, and the answer would incorrectly be 0. Starting at arr[0] correctly returns -1. This is the single most common bug in Kadane's algorithm.

5. The equivalent "reset to 0" form

Many implementations write Kadane's algorithm as:

long long best = arr[0], current = 0;
for (int i = 0; i < n; i++) {
    current += arr[i];
    if (current > best) best = current;
    if (current < 0) current = 0;
}
                                

This is mathematically equivalent to the max-based form: when current + arr[i] < arr[i], it means current < 0, so arr[i] is chosen β€” equivalent to resetting to 0 and adding arr[i]. Both compute the same current at every step. Use whichever reads clearer to you; the max version is arguably more explicit about the two-way choice.

6. Tracking the subarray bounds

The maxSubarrayWithBounds version adds three variables: curStart (where the current run began), bestStart, bestEnd. Each time we start fresh (because extending is worse), we update curStart = i. Each time we update best, we snapshot curStart and i into bestStart and bestEnd. The bookkeeping is minimal β€” the algorithm is unchanged.

7. Complexity

O(n) time β€” one pass, one comparison + one update per iteration. O(1) space β€” a handful of variables. Optimal. Compare with the naive O(nΒ²) approach (check every subarray's sum): for n=10,000, that's 50 million operations vs. 10,000. The speedup is 5,000Γ—. For larger arrays, the gap grows quadratically.

8. Why it's called Kadane's algorithm

The algorithm was published by Jay Kadane in 1984, in a paper about maximum-likelihood estimation for a statistical model. But it was already known as a solution to the maximum subarray problem β€” some sources credit Ulf Grenander (1977) or Michael Shamos (1978) with earlier versions. Kadane's name stuck because his was the clearest formulation, and because the problem appeared in a widely read textbook (Bentley's "Programming Pearls", 1986) with Kadane's solution as the elegant answer. It's one of the few algorithms known by a person's name outside of academic circles.

9. Relation to other problems

Kadane's algorithm is the gateway to many related problems:

  • Maximum product subarray: similar, but requires tracking both max and min (because multiplying by a negative flips the sign).
  • Maximum sum circular subarray: Kadane's plus Kadane's on the complemented array (via the "max = total - min" trick).
  • Maximum sum subarray with at most k negatives: a harder variant requiring a sliding window with a deque.
  • Maximum subarray sum modulo m: requires a different approach (prefix sums plus a balanced tree).
  • Maximum subrectangle sum (2D): Kadane's on the column-sum reduction, for each pair of rows.

Each of these builds on the core Kadane insight β€” track "best ending here" and "best overall" β€” with a twist. Mastering the basic version gives you the foundation for all of them.

10. Application to stock trading

One of the most common applications: given a series of daily stock prices, find the maximum profit from a single buy-sell pair. Compute the daily changes (price[i] - price[i-1]), then find the maximum-sum subarray of those changes. That's the maximum profit you could have made by buying at the start of the subarray and selling at the end. Kadane's algorithm solves this in O(n), which is faster than the naive O(nΒ²) approach (check every buy-sell pair). The same logic applies to any "maximum contiguous gain" problem, including currencies, commodities, and even energy prices β€” a classic application of a beautiful algorithm.

πŸ” Try this: implement the "maximum sum circular subarray" variant. The trick: the maximum-sum subarray either wraps around (doesn't include the middle) or doesn't wrap. For the non-wrapping case, use Kadane's. For the wrapping case, find the minimum-sum subarray and subtract it from the total. Take the max of the two. But be careful: if all elements are negative, the max is the non-wrapping answer (a single negative element), not the difference of two negatives.

Frequently Asked Questions

1. What does "contiguous" mean here?

It means the subarray must be a run of consecutive elements β€” no skipping. For [1, 2, 3, 4, 5], [2, 3, 4] is contiguous, but [1, 3, 5] is not (it skips 2 and 4). This distinguishes the problem from the "maximum sum subsequence" problem, where you can pick any elements. For subsequences, the max sum is just the sum of all positive elements β€” much easier, and Kadane's algorithm doesn't apply. The "contiguous" restriction is what makes the problem interesting.

2. Why does initializing to arr[0] matter?

Because if all elements are negative, the maximum-sum subarray is the single largest (least negative) element. For [-3, -1, -4, -2], the answer is -1. If you initialized best = 0, the algorithm would never find anything better than 0 (since all intermediate sums are negative), and it would incorrectly return 0. Initializing to arr[0] ensures the correct answer for all-negative arrays. This is the single most common bug in Kadane's algorithm implementations.

3. Why reset the running sum to 0 when it goes negative?

Because a negative prefix is a liability β€” any subarray that includes it would be better off starting after it. Think of it this way: if you're trying to maximize a sum, and your running total is already negative, adding more numbers to it only makes sense if those numbers are large enough to overcome the negative. But if you instead drop the negative prefix entirely and start fresh, you always get a larger sum. So the local optimization "reset to 0" is globally correct β€” it's the optimal decision at every step.

4. Can the maximum subarray be empty?

In the standard problem, no β€” you must pick at least one element. If the problem allowed an empty subarray (sum 0), you'd initialize best = 0 and the answer for all-negative arrays would be 0 (the empty subarray). Both interpretations exist in the wild, so read the problem statement carefully. LeetCode's "Maximum Subarray" problem (LeetCode #53) requires a non-empty subarray, which is the standard interpretation β€” the one our program implements.

5. How does this relate to the maximum product subarray?

The product version is a close relative but requires tracking two variables (max and min) instead of one, because multiplying by a negative flips the sign. In the sum case, a negative running sum is always bad (so reset). In the product case, a large negative product can become a large positive product after the next negative β€” so you must track both the maximum and the minimum product ending at each position. The two-variable version is what makes the product variant work.

6. Can Kadane's algorithm work on 2D arrays?

Yes β€” for the maximum-sum subrectangle problem. The idea: for each pair of rows (top, bottom), compute the column-wise sum between those rows (giving a 1D array), then run Kadane's algorithm on that 1D array. The maximum over all pairs is the answer. Complexity is O(rowsΒ² Γ— cols) β€” much better than the naive O(rowsΒ³ Γ— colsΒ³) approach, but still slower than the 1D case. This is a classic interview problem and a natural extension of the 1D algorithm.

πŸ’‘ Tip: Once this works, try the "best time to buy and sell stock" problem β€” it's a small variation where you compute the daily changes and run Kadane's algorithm on them. Then try the "best time to buy and sell stock with cooldown" problem β€” a different structure entirely, but the same underlying idea of tracking local state as you scan. These three problems form a nice triad that teaches you how the same basic algorithm adapts to different constraints.

πŸ“– Related Tutorials

  • Introduction to Functions in C
  • One Dimensional Arrays
  • Passing Arrays to Functions
  • Function Definition
  • Function Declaration
  • Previous: Find the Maximum Product Subarray
  • All 33 Function Assignments

Previous Topic: -->> 32. Find the Maximum Product Subarray Using a Function   ||   All Assignments: -->> All 33 Function Assignments


C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • CONDITIONAL STATEMENTS
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • LOOPS STATEMENTS
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processiong
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ