列表

详情


AB33. 相差不超过k的最多数

描述

给定一个数组,选择一些数,要求选择的数中任意两数差的绝对值不超过 k 。问最多能选择多少个数?

输入描述

第一行输入两个正整数 nk
第二行输入 n 个正整数a_i,用空格隔开,表示这个数组。

输出描述

一个正整数,代表能选的最多数量。
数据范围:

示例1

输入:

5 3
2 1 5 3 2

输出:

4

说明:

显然,1和5不能同时选。所以最多只能选4个数。

原站题解

C++ 解法, 执行用时: 37ms, 内存消耗: 1192KB, 提交时间: 2022-05-08

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define endl '\n'
#define rep(x,a,b) for(int (x)=(a);(x)<(b);(x)++)
const int N = 1e9 + 1;
int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int n, k, ans = 0, l = 0, r = 0;
    cin >> n >> k;
    int a[n];
    rep(i, 0, n)cin >> a[i];
    sort(a, a + n);
    while (r < n) {
        if (a[r] - a[l] <= k)ans = max(ans, r - l + 1);
        else l++;
        r++;
    }
    cout << ans;
    return 0;
}

C++ 解法, 执行用时: 41ms, 内存消耗: 1588KB, 提交时间: 2022-08-03

#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    int n, k;
    cin >> n >> k;
    vector<int> arr;
    for (int i = 0; i != n; ++i) {
        int x;
        cin >> x;
        arr.push_back(x);
    }
    sort(arr.begin(), arr.end());
    int sum = 1;
    for (int l = 0, r = 0; r != n; ++r) {
        if (l < r) {
            if (abs(arr[r]-arr[l]) <= k) ++sum;
            else ++l;
        }
    }
    cout << sum;
    return 0;
}

C++ 解法, 执行用时: 42ms, 内存消耗: 1196KB, 提交时间: 2022-04-15

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define endl '\n'
#define rep(x,a,b) for(int (x)=(a);(x)<(b);(x)++)
const int N=1e9+1;
int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int n,k,ans=0,l=0,r=0;
    cin>>n>>k;
    int a[n];
    rep(i,0,n)cin>>a[i];
    sort(a,a+n);
    while(r<n){
        if(a[r]-a[l]<=k)ans=max(ans,r-l+1);
        else l++;
        r++;
    }
    cout<<ans;
    return 0;
}

C++ 解法, 执行用时: 43ms, 内存消耗: 1220KB, 提交时间: 2022-07-13

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main(){
    ios::sync_with_stdio(false);
    int n,k;
    cin>>n>>k;
    vector<int> vec(n,0);
    for(int i=0;i<n;i++){
        cin>>vec[i];
    }
    sort(vec.begin(),vec.end());
    int l = 0;
    int ans = 0;
    for(int r = 0;r<n;r++){
        while(vec[r]-vec[l]>k){
            l++;
        }
        ans = max(ans, r-l+1);
    }
    cout<<ans;
    return 0;
}

C++ 解法, 执行用时: 43ms, 内存消耗: 1244KB, 提交时间: 2022-06-19

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;

int main()
{
	int n, k;
	cin >> n >> k;
	vector<int>vec(n,0);
	for (int i = 0; i < n; i++)
	{
		scanf("%d",&vec[i]);
	}
	sort(vec.begin(), vec.end());
	int l = 0;;
	int ans = 0;
	for (int r = 0; r < n; r++)
	{
		while (vec[r] - vec[l] > k)
		{
			l++;
		}
		ans = max(ans, r - l + 1);
	}
	cout << ans;
	return 0;
}

上一题