题目大意
给定一个n个数的数组,从里面按顺序选择任意个数,使选择的数中任意两个数的差值的绝对值要小于k,求出最多能选多少个数。
贪心
对原数组进行排序,从小到大选择最小满足要求的即可。
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main()
{
int n, k;
cin >> n >> k;
vector<int> a(n);
for (auto& i: a)
{
cin >> i;
}
sort(a.begin(), a.end());
int ans = 1;
int t = a[0];
for (int i = 1; i < n; i++)
{
if (a[i] - t >= k)
{
t = a[i];
ans++;
}
}
cout << ans << endl;
return 0;
}
该篇博客介绍了如何解决一个关于数组中选取元素的问题,通过贪心策略对数组排序,找出满足任意两个数差值绝对值小于k的最大数量。代码实例展示了C++实现方法。

1202

被折叠的 条评论
为什么被折叠?



