Maximum subarray (Kadane) in C: solved exercise

Maximum subarray (Kadane) in C: solved exercise

If you are looking for maximum subarray (kadane) in c: solved exercise, here is a practical, compilable example focused on the reusable idea behind the exercise.

Problem statement

Compute the maximum contiguous subarray sum in {-2,1,-3,4,-1,2,1,-5,4}.

C solution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
#include <stdio.h>

int kadane(const int a[], int n) {
    int mejor = a[0];
    int actual = a[0];

    for (int i = 1; i < n; i++) {
        actual = (actual + a[i] > a[i]) ? actual + a[i] : a[i];
        mejor = (mejor > actual) ? mejor : actual;
    }
    return mejor;
}

int main(void) {
    int a[] = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
    printf("%d\n", kadane(a, 9));
    return 0;
}

Expected output

1
6

Common mistakes

  • Not testing edge cases such as small or empty inputs.
  • Not validating indices, pointers, or limits carefully enough.
  • Copying the mechanics without understanding the general pattern.

Practical use

The key idea is to identify a reusable pattern instead of stopping at “it works once”.

Guided practice and full book

If you want a complete path with progressive difficulty:

FAQ

Is this exercise useful in practice?

Yes. It is designed to teach a reusable C pattern rather than a one-off toy example.

How should I practice it better?

Change the input data, add edge cases, and rewrite it from scratch without looking at the solution.

How should I practice this exercise type to improve faster?

Start with small inputs, run edge cases (empty, one item, max capacity), then rewrite the solution from scratch without copying.