试题原文链接:
点击打开链接
试题要求翻译如下:给定的一段数字序列,求出最大连续子序列和大小,并得出起始位置和结束位置序号,并用空格间隔输出。
例子:
input:
10
-10 1 2 3 4 -5 -23 3 7 -21
output:
10 1 4
代码设计如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int* pList = NULL;
char* dot = NULL;
char* buffer = NULL;
int length = 0;
int index = 0;
int FindMaxSubsequenceSum1()
{
int firstSum = 0;
int backupSum = 0;
int startPos = 0;
int lastPos = 0;
for ( int i = 0; i < length; i++ )
{
int secondSum = 0;
for ( int j = i; j < length; j++ )
{
secondSum += pList[j];
if ( secondSum > firstSum )
{
firstSum = secondSum;
lastPos = j;
}
}
if ( firstSum > backupSum )
{
backupSum = firstSum;
startPos = i;
}
}
printf( "%d %d %d", firstSum, startPos, lastPos );
return 0;
}
/*int FindMaxSubsequenceSum2()
{
return 0;
}*/
int main()
{
printf( "Please the length of Array:\n");
//length = 12;
scanf( "%d", &length );
pList = (int*)malloc( length*sizeof(int) );
buffer = (char*)malloc( length*sizeof(char) );
printf( "Please Input the content of array:\n");
//strcpy(buffer,"-6 2 4 -7 5 3 2 -1 6 -9 10 -2");
getchar();
scanf( "%[^\n]", buffer );
dot = strtok( buffer, " " );
while ( dot != NULL )
{
pList[index++] = atoi(dot);
dot = strtok( NULL, " " );
}
FindMaxSubsequenceSum1();
printf( "\n" );
return 0;
}