/********************************** 求数组中连续字串的最大和 并返回起始位置和终止位置 ***********************************/ #include <stdio.h> #define elemType int elemType max(elemType a,elemType b) { if(a>b) return a; return b; } elemType maxSumOfContinueSubStr(elemType *a,int length) { if(a == NULL || length <= 0) return 0; int maxSum=0,sumOfEnd=0; int leftIndex=0,rightIndex=-1; for(int i=0;i<length;i++) { sumOfEnd = max(0,sumOfEnd+a[i]); if(sumOfEnd == 0) leftIndex = i+1+1; //下一个位置开始 maxSum = max(maxSum,sumOfEnd); if(maxSum == sumOfEnd) rightIndex = i+1; //当前位置 } printf("from: %d to %d",leftIndex,rightIndex); return maxSum; } void main() { elemType a[11] = {-3,2,-1,2,-4,5,6,4,-9,1,2}; elemType sum = maxSumOfContinueSubStr(a,10); printf("max sum of continue sub str is:%d\n",sum); }