Skip to content

Instantly share code, notes, and snippets.

@sumanth232
Created August 24, 2013 12:22
Show Gist options
  • Save sumanth232/d19fa81e30e5bd394a94 to your computer and use it in GitHub Desktop.
Save sumanth232/d19fa81e30e5bd394a94 to your computer and use it in GitHub Desktop.
Finds the maximum contiguous sum in an array
#include <stdio.h>
#include <stdlib.h>
int max_subarray_sum(int a[],int size)
{
int i;
int cumulative_sum = a[0];
int maxsofar = a[0];
int cumulative_min = a[0];
for(i=1; i<size; i++)
{
cumulative_sum = cumulative_sum + a[i];
if(cumulative_sum - cumulative_min > maxsofar) maxsofar = cumulative_sum - cumulative_min;
if(cumulative_sum < cumulative_min) cumulative_min = cumulative_sum;
}
return maxsofar;
}
int main()
{
int ar[] = {-2, -3, 4, -1, -2, 1, 5, -3};
printf("%d\n", max_subarray_sum(ar, sizeof(ar)/sizeof(ar[0])));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment