钻石收藏家

奶牛贝茜非常喜欢闪闪发光的东西,她会在业余时间开采钻石。

她收藏了 N 颗大小不等的钻石,她想将其中的一些摆放在牛棚的展示柜当中。

为了使展示柜中的钻石尺寸大小相似,她不会将两颗尺寸大小相差超过 K 的钻石同时放在柜子中(刚好相差 K,则没有问题)。

给定 K,请帮助贝茜计算在展示柜中最多可以摆放多少颗钻石。

输入格式

第一行包含两个整数 N,K。

接下来 N 行,每行包含一个整数,表示一颗钻石的尺寸。

输出格式

输出贝茜可以在展示柜中展示的钻石最大数量。

数据范围

1≤N≤1000,
0≤K≤10000,
钻石的尺寸范围 [1,10000]

输入样例:

5 3
1
6
4
3
1

输出样例:

4

源代码 

#include <iostream>
#include <algorithm>
using namespace std;
const int N = 1000+10;
int a[N]={0};
int main()
{
	int n,k;
	cin>>n>>k;
	for(int i = 1;i <= n;i ++ )cin>>a[i];
	sort(a+1,a+1+n);//排序
	int ans=0;
	for(int i = 1;i <= n;i ++ )//依次查长度
	{
		int idx=i;
	 	while(abs(a[idx]-a[i])<=k&&idx<=n)idx++;//使用while循环查另一端点
		ans=max(ans,idx-i);//求此段长度求最大值
	}
	cout<<ans;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/couchpotatoshy/article/details/124546101