data-structures · intermediate · ~15 min
Find the largest sum of a contiguous subarray.
Implement:
long long max_subarray(const int *a, int n);
Return the maximum sum of a non-empty contiguous subarray (Kadane's algorithm). n >= 1.
Array a, count n>=1.
Maximum contiguous sum.
Handle all-negative arrays (answer is the largest element).
#include <stddef.h>
/* Maximum sum of a non-empty contiguous subarray (Kadane). n>=1. */
long long max_subarray(const int *a,int n){ (void)a;(void)n; return 0; }
Resetting the running sum to 0 (wrong for all-negative inputs) instead of starting a fresh subarray.
Single element -> that element.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.