code4sk/c/sourcecode/AlgorithmO/20230911/最大子段和问题3.c
2023-10-18 16:17:32 +08:00

51 lines
1.3 KiB
C
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/*
C. 最大子段和问题
Description
给定n个整数可能为负数a1,a2,……an。求ai,ai+1,……aj其中i<=i<=j<=n的子段和的最大值。当所有整数均为负数时我们定义其最大子段和为0此时From为1To为n。例如a1,a2,a3,a4,a5,a6=-2,11,-4,13,-5,-2最大子段和为a2+a3+a4=20i=2,j=4下标从1开始这个问题我们称之为“最大子段和问题”。
Input
本问题有多组测试数据每组数据有两行第一行为nn<=1000第二行有n个整数数与数之间用空格隔开。
Output
参见样例格式
Sample Input
6
-2 11 -4 13 -5 -2
Sample Output
From=2,To=4
MaxSum=20
*/
#include <stdio.h>
int a[1001],n,max,from,to,s;
int main()
{
int i,j,n;
while(1==scanf("%d",&n))
{
for(i=1;i<=n;i++)
{
scanf("%d",&a[i]);
}
from=1;
to=n;
max=0;
for(i=1;i<=n;i++)
{
s=0;
for(j=i;j<=n;j++)
{
s+=a[j];
if(max<s)
{
max=s;
from=i;
to=j;
}
}
}
printf("From=%d,To=%d\n",from,to);
printf("MaxSum=%d\n",max);
}
return 0;
}