Created
August 24, 2013 12:22
-
-
Save sumanth232/d19fa81e30e5bd394a94 to your computer and use it in GitHub Desktop.
Finds the maximum contiguous sum in an array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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