数组中,一部分整数,一部分复数;当然可能全是复数。
求出这个数值中能够得到最大和的子序列。
原理:用动态规划方法。一个临时变量记录从上一次负数开始的临时最大值的序列,如果它比上一个temp值大的话,就用它替代上一个成为最大的子值。
注意:最后有一步骤检查,看是否全部的数据都是负数,如果是的话,重新搜索一遍数组找到最小的负数,作为最大子序列的值。
- bool FindGreatestSumOfSubArray(
- int *pData, // an array
- unsigned int nLength, // the length of array
- int &nGreatestSum // the greatest sum of all sub-arrays
- ){
- // if the input is invalid, return false
- if((pData == NULL) || (nLength == 0))
- return false;
- int nCurSum = nGreatestSum = 0;
- for(unsigned int i = 0; i < nLength; ++i){
- nCurSum += pData[i];
- // if the current sum is negative, discard it
- if(nCurSum < 0)
- nCurSum = 0;
- // if a greater sum is found, update the greatest sum
- if(nCurSum > nGreatestSum)
- nGreatestSum = nCurSum;
- }
- // if all data are negative, find the greatest element in the array
- if(nGreatestSum == 0){
- nGreatestSum = pData[0];
- for(unsigned int i = 1; i < nLength; ++i){
- if(pData[i] > nGreatestSum)
- nGreatestSum = pData[i];
- }
- }
- return true;
- }
- int main(int argc, char* argv[]){
- int arr[] = {1,8,3,-6,9,4,-10,12,99};
- int result = 0;
- if ( FindGreatestSumOfSubArray( arr, sizeof(arr)/sizeof(int), result ))
- printf( "Hello World:%d", result);
- else
- printf( "Bad Hello World:%d", result);
- return 0;
- }