Function Assignment 28 — Find the Largest Sum Subarray Using a Function
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Find the Largest Sum Subarray Using a Function

📑 On this page:
  • What "largest sum subarray" means
  • 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 sum of one can be maximized efficiently
  • Kadane's algorithm — the O(n) insight that solves this in one pass
  • Why resetting a negative running sum to 0 is the correct (and subtle) move
  • How to handle all-negative arrays correctly
  • How Kadane's algorithm extends to tracking the actual subarray bounds, not just the sum

What "largest sum subarray" means

A contiguous subarray is a slice of an array — a run of consecutive elements, from some index i to some index j with i ≤ j. For the array [1, -2, 3, 4, -1, 2], valid subarrays include [1], [1, -2], [3, 4], [3, 4, -1, 2], and the full array itself. The "largest sum subarray" problem asks: among all contiguous subarrays, which one has the maximum sum, and what is that sum?

For [1, -2, 3, 4, -1, 2], the largest-sum subarray is [3, 4, -1, 2] with sum 8. The trick is that including some negative elements can still be worth it — the -1 in the middle is "carried" by the surrounding positive runs. The naive approach — check every possible subarray — is O(n²) or O(n³) depending on how you sum them. For an array of 10,000 elements, that's 100 million to 10¹² operations. Way too slow for anything but toy inputs.

Kadane's algorithm solves this in O(n) — one pass, one running sum, one maximum. The insight is beautifully simple: as you scan the array left to right, keep a running sum of "the best subarray ending at the current position." If that sum ever goes negative, reset it to 0 — a negative prefix can't help any future subarray, so it's better to start fresh. Meanwhile, track the maximum value that the running sum has ever reached. That maximum is your answer. One pass, two variables, done.

This is one of the most elegant algorithms in competitive programming, and it appears in dozens of interview questions. It also generalizes in surprising ways: to 2D arrays (maximum sum subrectangle), to circular arrays, to subarrays with a fixed sum, and more. Understanding Kadane's algorithm is one of the highest-value investments you can make as a programmer — it's a small insight with a large payoff.

💡 In one line: iterate once, updating current = max(arr[i], current + arr[i]) and best = max(best, current). If current is the best sum ending at i, and best is the best sum seen anywhere, then best is your answer.

An array with a highlighted subarray [3, 4, -1, 2] summing to 8 — the maximum contiguous sum.

Kadane's algorithm — the O(n) insight

Here's the algorithm in pseudocode:

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

for i from 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. Done. The magic is in what current means: it's the maximum sum of a subarray ending at index i. That's a subtle but crucial restriction. By focusing on subarrays ending at i, we reduce the problem to "should I include arr[i] in the best subarray ending at i-1, or start fresh at arr[i]?" The answer is the max of those two options — and that's exactly what max(arr[i], current + arr[i]) computes.

Let's trace it for [1, -2, 3, 4, -1, 2]:

i arr[i] current best Reason
0111Initial values
1-2-11max(-2, 1-2) = -1
2333max(3, -1+3) = 3 (fresh start)
3477max(4, 3+4) = 7
4-167max(-1, 7-1) = 6
5288max(2, 6+2) = 8

The maximum is 8, achieved at the end by the subarray [3, 4, -1, 2]. The key moment is at i = 2 (value 3): current was -1, which is worse than starting fresh at 3, so we reset. That's Kadane's insight in action — a negative prefix is never worth including.

🎯 The insight: the best subarray ending at i is either arr[i] alone (starting fresh), or arr[i] appended to the best subarray ending at i-1. That's max(arr[i], current + arr[i]) — two choices, no more. This local decision is correct globally, which is why Kadane's algorithm works.

Complete C Program

Program: read an array, find the maximum subarray sum

#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 subarray sum: %lld\n", maxSubarraySum(arr, n));

    return 0;
}

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

    for (int i = 1; i < n; i++) {
        current += arr[i];
        if (current < arr[i]) {
            current = arr[i];   /* restart with just arr[i] */
        }
        if (current > best) {
            best = current;
        }
    }
    return best;
}
                                    

And a version that also reports which subarray achieves the maximum — much more useful in practice, since the sum alone doesn't tell you where the answer came from:

Variant: report start and end indices

#include <stdio.h>

long long maxSubarrayWithBounds(const int arr[], int n,
                                int *outStart, int *outEnd) {
    long long best = arr[0];
    long long current = 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[] = {1, -2, 3, 4, -1, 2};
    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 bookkeeping is minimal — one additional variable to remember where the current run started, and two more to record where the best run was found. The result is much more useful: not just "the max is 8" but "the max is 8, from arr[2] to arr[5] (values 3, 4, -1, 2)." In a real application, you almost always want this extra information.

And a version that uses Kadane's on a circular array — where the subarray can wrap around from the end to the beginning:

Variant: maximum subarray for circular arrays

#include <stdio.h>

long long maxSubarrayCircular(const int arr[], int n) {
    long long maxStraight = arr[0];
    long long curMax = arr[0];
    long long minStraight = arr[0];
    long long curMin = arr[0];
    long long total = arr[0];

    for (int i = 1; i < n; i++) {
        total += arr[i];

        curMax = (curMax + arr[i] > arr[i]) ? curMax + arr[i] : arr[i];
        if (curMax > maxStraight) maxStraight = curMax;

        curMin = (curMin + arr[i] < arr[i]) ? curMin + arr[i] : arr[i];
        if (curMin < minStraight) minStraight = curMin;
    }

    if (maxStraight < 0) return maxStraight;      /* all negative */
    long long maxWrapped = total - minStraight;
    return (maxStraight > maxWrapped) ? maxStraight : maxWrapped;
}

int main(void) {
    int arr[] = {5, -3, 5};
    int n = sizeof(arr) / sizeof(arr[0]);
    printf("Max circular subarray sum: %lld\n", maxSubarrayCircular(arr, n));
    return 0;
}
                                

The circular version handles the case where the best subarray wraps around. For [5, -3, 5], the best subarray is [5, 5] (wrapping around), sum 10. The function computes this as total - minSubarray — the complement of the minimum subarray. This is a classic competitive-programming trick, and it builds directly on Kadane's algorithm.

Program Output

A typical run:

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

The max sum is 8, achieved by the subarray [3, 4, -1, 2]. The -2 is excluded (starting fresh after it gave a better result), and the -1 is included (the surrounding positives outweigh it).

With all-negative input:

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

When all elements are negative, the maximum subarray is just the single largest element (in this case, -1). This is why initializing best = arr[0] and current = arr[0] is critical — starting at 0 would incorrectly return 0 for an all-negative array. The Kadane's algorithm must include at least one element in the subarray; it doesn't allow the empty subarray (sum 0) as an answer.

With an all-positive array:

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

When everything is positive, the maximum subarray is the entire array — the sum of all elements. Kadane's algorithm handles this naturally: current keeps growing, and best tracks it. No special-casing needed.

A single element:

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

The loop doesn't execute (there's no i=1), so the function returns arr[0] = 42, which is correct — the only subarray is the single element.

And the bounds-reporting variant:

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

Not only does the function tell you the maximum sum is 8, it tells you exactly where it comes from — indices 2 through 5, values 3, 4, -1, 2. That's the kind of answer that's actually useful in a real application.

And the circular variant:

Max circular subarray sum: 10
                                

For [5, -3, 5], the maximum sum is 10, achieved by taking both 5s (wrapping around the middle). The straight subarray sum is 7 (just [5, -3, 5]), but the wrapped version does better by including both ends and skipping the middle.

Step-by-Step Explanation

Let's dig into why Kadane's algorithm works, and how the code implements it.

1. The key insight

Focus on the subarray ending at position i. This subarray is either:

  • Just arr[i] (a single-element subarray).
  • The best subarray ending at i-1, extended by arr[i].

Those are the only two possibilities, because any subarray ending at i has to include arr[i], and the part before it is a subarray ending at i-1. If we want the maximum, we want whichever of these two is larger:

current = max(arr[i], current + arr[i]);
                                

This is the entire recurrence. The max picks between "start fresh" (just arr[i]) and "extend" (current + arr[i]). If extending gives a lower sum than starting fresh, we start fresh. If extending gives a higher sum, we extend.

2. Why this is optimal

The recurrence is exact — no approximation. For any i, current is precisely the maximum sum of a subarray ending at i. This is provable by induction: at i = 0 it's trivially true (only one choice). At i > 0, the maximum either includes arr[i] alone or extends the best at i-1, and we take the better of the two.

Then best = max(best, current) tracks the maximum over all i. So best is the maximum sum of any subarray ending at any position — which is the maximum sum of any contiguous subarray, period. QED.

3. Tracing maxSubarraySum for [1, -2, 3, 4, -1, 2]

Already traced in the table above, but here in prose:

  1. Init: best = 1, current = 1.
  2. i=1, arr[1] = -2. current = max(-2, 1-2) = max(-2, -1) = -1. best = max(1, -1) = 1.
  3. i=2, arr[2] = 3. current = max(3, -1+3) = max(3, 2) = 3. best = max(1, 3) = 3.
  4. i=3, arr[3] = 4. current = max(4, 3+4) = max(4, 7) = 7. best = max(3, 7) = 7.
  5. i=4, arr[4] = -1. current = max(-1, 7-1) = max(-1, 6) = 6. best = max(7, 6) = 7.
  6. i=5, arr[5] = 2. current = max(2, 6+2) = max(2, 8) = 8. best = max(7, 8) = 8.

Final best = 8. ✓

4. Why the algorithm is O(n)

One loop over the array. Two comparisons per iteration. No nested loops, no backtracking. That's O(n) time and O(1) space. You can't do better than O(n) for this problem — you have to look at every element at least once to be sure you haven't missed a better subarray. So Kadane's algorithm is optimal.

Compare with the naive O(n²) approach (check every start-end pair) or O(n³) (sum each subarray from scratch). For n=1000, that's a million to a billion operations vs. 1000. For n=10,000, the gap is enormous.

5. The all-negative edge case

The initialization best = arr[0] and current = arr[0] is essential for all-negative arrays. If you initialized to 0, the algorithm would return 0 for an array like [-3, -1, -4, -2], which is wrong — the maximum subarray sum is -1, not 0. The empty subarray (sum 0) is not considered a valid answer; the problem requires a non-empty subarray.

This is one of the most common bugs in Kadane's algorithm. Initializing to arr[0] handles all cases correctly, including all-negative and single-element inputs.

6. The equivalent "reset to 0" form

Many implementations write Kadane's algorithm differently:

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

This version initializes current = 0 and resets it to 0 whenever it goes negative. It's mathematically equivalent to the max-based version, but it has the same all-negative bug if you're not careful with best. If you initialize best = arr[0] and this loop runs, it works correctly. If you initialize best = 0, you get wrong answers for all-negative arrays.

7. Tracking the subarray bounds

The variant that reports start and end indices adds three more variables: curStart (where the current run started), bestStart, and bestEnd. Every time we start fresh at arr[i] (because current + arr[i] < arr[i]), we set curStart = i. Every time we update best, we record the current run's bounds. At the end, we have the exact subarray. This is a small extension but a large practical improvement — the sum alone is rarely enough to act on.

8. Extension: max sum subarray in a 2D matrix

Kadane's algorithm extends to 2D: for each pair of rows (top, bottom), compute the column-wise sum, and run Kadane's algorithm on that 1D array. This gives the maximum-sum subrectangle. It's O(rows² × cols) — much better than the O(rows³ × cols³) naive approach, but still slower than the 1D case. This is a classic interview problem, and it builds directly on the 1D algorithm.

9. Extension: maximum product subarray

A close relative is the maximum-product subarray problem. Kadane's algorithm doesn't apply directly because multiplying by a negative flips the sign, and the "minimum so far" can become the "maximum so far" after a negative. The fix is to track both maxProduct and minProduct ending at each position. When you hit a negative number, they swap roles — the current minimum becomes the basis for the next maximum. This is a nice demonstration of how a small change in the problem (sum → product) requires a small but crucial change in the algorithm (one variable → two variables).

10. Extension: fixed-length subarrays

If you want the maximum sum of a subarray of exactly length k, Kadane's algorithm doesn't quite apply — but a sliding window does. Sum the first k elements, then slide the window one element at a time: subtract the outgoing element, add the incoming one, track the maximum. That's O(n) too, and simpler than Kadane's for this specific problem. Each algorithm has its niche; using the right one for the problem at hand is a matter of experience.

🔍 Try this: implement the max-product subarray variant. Initialize both maxProd and minProd to arr[0]. For each element, compute three candidates — arr[i], maxProd × arr[i], and minProd × arr[i] — and set maxProd to the max, minProd to the min. Track the global best. The key insight: a negative number can turn the smallest product into the largest. Same skeleton as Kadane, one extra variable.

Frequently Asked Questions

1. Why does Kadane's algorithm work?

Because the best subarray ending at i is either just arr[i] (a fresh start) or the best subarray ending at i-1 extended by arr[i]. Those are the only two possibilities for a contiguous subarray that includes arr[i] as its last element. Since we're computing the best of these two at every step, we're effectively considering all possible subarrays — just efficiently. The recurrence is exact, so the answer is correct.

2. Why initialize to arr[0] and not 0?

Because if all elements are negative, the maximum subarray sum is negative (the least-negative element). Initializing to 0 would incorrectly return 0, which corresponds to the empty subarray — not a valid answer. Starting from arr[0] correctly handles the all-negative case. This is the single most common bug in Kadane's algorithm implementations.

3. What's the relationship between the two versions of Kadane's algorithm?

The "max" version (current = max(arr[i], current + arr[i])) and the "reset" version (if (current < 0) current = 0;) are mathematically equivalent. In the max version, 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 "start fresh or extend" decision.

4. How do I find the actual subarray, not just the sum?

Add three tracking variables: curStart (where the current run started), bestStart, and bestEnd. Update curStart = i whenever you start fresh at index i (i.e., current + arr[i] < arr[i]). Update bestStart and bestEnd whenever you update best. At the end, the subarray is arr[bestStart..bestEnd]. The extra bookkeeping is minimal — the algorithm structure is unchanged.

5. Can I use Kadane's algorithm on a 2D matrix?

Yes — for the max-sum subrectangle problem. For each pair of rows (top, bottom), compute the column-wise sum from top to bottom (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) — for a 1000×1000 matrix, that's 10⁹ operations, which is slow but tractable with good cache behavior. This is a classic interview problem and a natural extension of the 1D case.

6. Why does Kadane's algorithm handle all-negative arrays?

Because it starts with best = arr[0] and current = arr[0], not 0. For [-3, -1, -4, -2], the first iteration sets current = max(-1, -3 + (-1)) = max(-1, -4) = -1, and best = max(-3, -1) = -1. The rest of the iterations keep current at -1 (or lower), so best stays at -1. The algorithm correctly identifies the single largest element as the maximum subarray (a one-element subarray). If you wanted to allow the empty subarray (sum 0), you'd initialize best = 0, but that's a different problem.

💡 Tip: Once this works, try the max-product subarray problem — it's a small variant that teaches a big lesson about how state must be adapted to the operation. Then try the "max sum subarray with at most k negatives" — a harder problem that requires a more sophisticated data structure (typically a sliding window with a deque). Both are classic interview questions, and both build on the Kadane's skeleton you now understand.

📖 Related Tutorials

  • Introduction to Functions in C
  • One Dimensional Arrays
  • Passing Arrays to Functions
  • Function Definition
  • Function Declaration
  • Previous: Sum of Diagonal Elements in a Matrix
  • Next: Find the Longest Increasing Subsequence
  • All 33 Function Assignments

Previous Topic: -->> 27. Find the Sum of Diagonal Elements in a Matrix   ||   Next Topic: -->> 29. Find the Longest Increasing Subsequence Using a Function


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
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.