DATA STRUCTURES PROGRAM • ARRAY TECHNIQUES
Find the Maximum Subarray Sum with Kadane's Algorithm
Learn how to find the maximum subarray sum with kadane's algorithm using a clear C program.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
No input required
Sample output
Maximum subarray sum = 6
COMPLETE C PROGRAM
Complete C implementation
#include <stdio.h>
int main(void)
{
int values[] = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
int current = values[0], best = values[0];
for (int index = 1; index < 9; index++) {
current = values[index] > current + values[index] ? values[index] : current + values[index];
if (current > best) best = current;
}
printf("Maximum subarray sum = %d\n", best);
return 0;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
Maximum subarray sum = 6
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- At every position, choose between starting a new subarray and extending the current one.
- Display the computed result.
At every position, choose between starting a new subarray and extending the current one.
EFFICIENCY
Time and space complexity
Time complexity
O(n)
Auxiliary space
O(1)
DEBUGGING CHECKLIST
Common mistakes
Check this
Use the correct format specifier for every variable.
Check this
Initialize variables before using their values.
Check this
Check braces, semicolons and input order carefully.
Try it yourself
Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.
