//已知 有9,-8,1,-10,88,4,-5,7,9,-100,求最大子段和
#include "stdafx.h"
#include<iostream>
using namespace std;
#define iMAXSIZE (sizeof(iSrcArr)/sizeof(iSrcArr[0]))+100
//最大子段和
//
void getBiggestSum(int iSrcArr[],int iSize){//原数组,数组长度
int iSumArr[iMAXSIZE];
iSumArr[0] = iSrcArr[0];
int i,j;
for (int i = 1; i<iSize; i++){
if (iSumArr[i-1] + iSrcArr[i] > 0){//每次累加上一次的和只要大于0,就可以算入下一次的数值中
iSumArr[i] = iSumArr[i-1] + iSrcArr[i];
}else{
iSumArr[i] = 0;
}
}
int iStart = 0,iEnd = 0,iMaxSum = iSumArr[0];//起点,终点,和
for (int j = 1;j<iSize; j++){
if (iSumArr[j] > iMaxSum){//只要找出最大值,那么这个值就是所求的值
iMaxSum = iSumArr[j];
iEnd = j;
}
}
j = iEnd;
while (iSumArr[j]>0 && j>=0)j--;//找起点
iStart = j+1;
cout<<"start:"<<iStart+1<<" end:"<<iEnd+1<<" Sum:"<<iMaxSum<<endl;
return;
}
int _tmain(int argc, _TCHAR* argv[]){
int iSrcArr[] = {9,-8,1,-10,88,4,-5,7,9,-100};
getBiggestSum(iSrcArr,sizeof(iSrcArr)/sizeof(iSrcArr[0]));
return 0;
}