当前位置:网站首页>Haut OJ 1218: maximum continuous sub segment sum

Haut OJ 1218: maximum continuous sub segment sum

2022-07-05 05:17:00 hunziHang


Problem description :

give n Number , Find out n The sum of the largest continuous sub segments in the number .

Input :

The input is divided into two lines , The first line is a positive integer n, Second line input n It's an integer xi,

If the sum of the largest subsegments is negative , Output 0.

2<=n<=100000,-1000<=x<=1000.

Output :

Output the maximum continuous sub segment and .

The sample input :

5
1 2 -4 2 3

Sample output :

5


Cause analysis :

utilize sum And 0 The relationship between , To determine whether the previous data is valuable to the results , If the previous value is negative , The fu 0, It is equivalent to rewriting the starting sub column , If it is greater than 0 It means it is valuable , Can continue



Solution :

#include<stdio.h>
int main()
{
	int n, i, j, k, x, ans, sum;
	scanf("%d", &n);
	ans = 0;sum = 0;
	for (i = 1;i <= n;i++)
	{
		scanf("%d", &x);
		sum += x;
		if (sum > ans)
			ans = sum;
		if (sum < 0)
			sum = 0;
	}
	printf("%d\n", ans);
	return 0;
}

原网站

版权声明
本文为[hunziHang]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202140622509113.html