Skip to content

Commit

Permalink
Maximum subarray
Browse files Browse the repository at this point in the history
Signed-off-by: begeekmyfriend <[email protected]>
  • Loading branch information
begeekmyfriend committed Aug 25, 2017
1 parent a85c160 commit e698e78
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
2 changes: 2 additions & 0 deletions 053_maximum_subarray/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
all:
gcc -O2 -o test max_subarray.c
24 changes: 24 additions & 0 deletions 053_maximum_subarray/max_subarray.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>

static int maxSubArray(int* nums, int numsSize)
{
int i, max = INT_MIN, len = 0;
for (i = 0; i < numsSize; i++) {
len += nums[i];
/* Calculate maximum each time in loop */
max = len > max ? len : max;
if (len < 0) {
len = 0;
}
}
return max;
}

int main(int argc, char **argv)
{
int nums[] = { -2, 1, -3, 4, -1, 2, 1, -5, 4 };
printf("%d\n", maxSubArray(nums, sizeof(nums) / sizeof(*nums)));
return 0;
}

0 comments on commit e698e78

Please sign in to comment.