code4sk/c/sourcecode/AlgorithmO/20230911/最简单的“最大子段和”问题2.c
2023-10-18 16:17:32 +08:00

54 lines
1.5 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.

/*
B. 最简单的“最大子段和”问题
Description
给定n个整数可能为负数a1,a2,……an。求ai,ai+1,……aj 其中i<=i<=j<=n的子段和的最大值。当所有整数均为负数时我们定义其最大子段和为0且初始和终止位置也为0。例如a1,a2,a3,a4,a5,a6=-2,11,-4,13,-5,-2最大子段和为a2+a3+a4=20i=2,j=4下标从1开始这个问题我们称之为“最大子段和问题”。
在考试一上我们假定n<=200今天我们把n的范围规定修改为n<=2000你的任务是设计一个程序解决它。
Input
输入由两行第一行为n第二行为n个整数。
Output
输出也有两行第一行为“From=xxx,To=xxx”第二行为“MaxSum=xxxx”参见样例。
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;
}