大家好,我是小单同学,欢迎交流指正~
🎁题目: 钻石收藏家
奶牛贝茜非常喜欢闪闪发光的东西,她会在业余时间开采钻石。
她收藏了 N 颗大小不等的钻石,她想将其中的一些摆放在牛棚的展示柜当中。
为了使展示柜中的钻石尺寸大小相似,她不会将两颗尺寸大小相差超过 K 的钻石同时放在柜子中(刚好相差 K,则没有问题)。
给定 K,请帮助贝茜计算在展示柜中最多可以摆放多少颗钻石。
输入格式
第一行包含两个整数 N,K
接下来 N 行,每行包含一个整数,表示一颗钻石的尺寸。
输出格式
输出贝茜可以在展示柜中展示的钻石最大数量。
数据范围
1≤N≤1000
0≤K≤10000
钻石的尺寸范围 [1,10000]输入样例:
5 3 1 6 4 3 1
输出样例:
4
暴力枚举就可以做,这道题实质上就是问你满足最大数减去最小数的差<=k 的最长区间。
可以枚举所有区间,O(n^2),不会超时,也可以用双指针优化。
🍞代码详解
暴力枚举:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int N = 1005;
int a[N];
int f[N];
int n,k;
int main(){
cin >> n >> k;
for(int i = 0;i < n;i++){
scanf("%d",&a[i]);
}
sort (a,a+n);
int ans = 0;
for(int i=0;i<n;++i)
for(int j=i;j<n;j++){
if(a[j]-a[i]<=k)ans = max(ans,j-i+1);
else continue;
}
cout << ans;
return 0;
}
双指针:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int N = 1005;
int a[N];
int f[N];
int n,k;
int main(){
cin >> n >> k;
for(int i = 0;i < n;i++){
scanf("%d",&a[i]);
}
sort (a,a+n);
int ans = 0;
for(int i=0,j=0;i<n;++i){
while(a[i]-a[j] > k)j++;
ans = max(ans,i-j+1);
}
cout << ans;
return 0;
}
坚持跟y总每天打卡一道算法题~