Skip to content

Commit a31a630

Browse files
committed
添加以线性方法来求解最大子数组的代码
1 parent cf2a967 commit a31a630

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
#include <stdio.h>
2+
#include <limits.h>
3+
#include <stdlib.h>
4+
5+
int getMaxSubArray(const int inputArray[] , const int arrayLength , int * leftBorder , int * rightBorder)
6+
{
7+
int left ; int right;
8+
int sum=0;
9+
int max=INT_MIN;
10+
int i=0;
11+
left = 0;
12+
for(i=0;i<arrayLength ; ++i)
13+
{
14+
sum+=inputArray[i];
15+
if(sum < 0)
16+
{
17+
sum = 0;
18+
left = i+1;
19+
}
20+
if(sum > max)
21+
{
22+
max = sum;
23+
right = i;
24+
}
25+
}
26+
*leftBorder = left;
27+
*rightBorder = right;
28+
return max;
29+
}
30+
31+
int main(int argc, char const *argv[])
32+
{
33+
const int array[]={13,-3,-25,20,-3,-16,-23,18,20,-7,12,-5,-22,15,-4,7};
34+
int leftBorder,rightBorder;
35+
int max = getMaxSubArray(array , sizeof(array)/sizeof(int) , &leftBorder , &rightBorder);
36+
printf("from %d to %d is the max sub array and the max value is : %d \n",leftBorder , rightBorder , max );
37+
return 0;
38+
}

0 commit comments

Comments
 (0)