求一个数组的相加和最大的连续子数组
思路:
一直累加,只要大于0,就说明当前的“和”可以继续增大,
如果小于0了,说明“之前的最大和”已经不可能继续增大了,就从新开始,
result=max{result+arr[i],arr[i]};//显然,若result>0,则可以继续相加,否则,就重新开始。
#include<stdio.h> #define INF 65535 int Maxsum(int * arr, int size) { int maxSum = -INF; int sum = 0; for(int i = 0; i < size; ++i) { if(sum < 0) { sum = arr[i]; }else { sum += arr[i]; } if(sum > maxSum) { maxSum = sum; } } return maxSum; } void Maxsum_location(int * arr, int size, int & start, int & end) { int maxSum = -INF; int sum = 0; int curstart = start = 0; /* curstart记录每次当前起始位置 */ for(int i = 0; i < size; ++i) { if(sum < 0) { sum = arr[i]; curstart = i; /* 记录当前的起始位置 */ }else { sum += arr[i]; } if(sum > maxSum) { maxSum = sum; start = curstart; /* 记录并更新最大子数组起始位置 */ end = i; } } } void main() { /* 测试用例 */ //int arr[] = {8,-10,3,60,-1,-6}; int arr[] = {1,-2,3,5,-1,2}; int arr2[] = {-9,-2,-3,-5,-4,-6}; int len = sizeof arr / sizeof(int); int len2 = sizeof arr2 / sizeof(int); /* 测试实现 */ printf("%d %d ",Maxsum(arr,len),Maxsum(arr2,len2)); /* 返回起始位置 */ int start = -1; int end = -1; Maxsum_location(arr,len,start,end); printf("start:%d end:%d ", start, end); Maxsum_location(arr2,len2,start,end); printf("start:%d end:%d ", start, end); }