J - Java Beans

本文介绍了一种解决环形序列中寻找连续子序列最大值的算法问题,通过实例演示了如何通过一次遍历实现最优解,适用于竞赛编程及算法优化场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

There are N little kids sitting in a circle, each of them are carrying some java beans in their hand. Their teacher want to select M kids who seated in M consecutive seats and collect java beans from them.

The teacher knows the number of java beans each kids has, now she wants to know the maximum number of java beans she can get from M consecutively seated kids. Can you help her?

Input

There are multiple test cases. The first line of input is an integer T indicating the number of test cases.

For each test case, the first line contains two integers N (1 ≤ N ≤ 200) and M (1 ≤ MN). Here N and M are defined in above description. The second line of each test case contains N integers Ci (1 ≤ Ci ≤ 1000) indicating number of java beans the ith kid have.

<h4< dd="">
Output

For each test case, output the corresponding maximum java beans the teacher can collect.

<h4< dd="">
Sample Input
2
5 2
7 3 1 3 9
6 6
13 28 12 10 20 75
<h4< dd="">
Sample Output
16
158
将要查找的序列看为一个环,比较一周,找其中最大值
#include<stdio.h>
int main()
{
	int t,n,m,a[200],i,sum=0,t2,t1,T;
	scanf("%d",&T);
	while(T--)
	{
		scanf("%d%d",&n,&m);
		for(i=0;i<n;i++)scanf("%d",&a[i]);
		sum=0;
		for(i=0;i<m;i++)sum+=a[i];
		if(n==m)printf("%d\n",sum);
		else{t1=0;t=sum;
			for(i=1;;i++)
			{
				if(i%n==0)break; t2=(i+m-1)%n;
				t=t-a[t1]+a[t2];
				t1=i%n;
				if(t>sum)sum=t;
				
			}
			printf("%d\n",sum);
		}
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值