列表

详情


NC231124. Strange_Integers

描述

Given n integers and a parameter k, you should choose some integers so that . Determine the maximum number of the integers you can choose.

输入描述

The first line contains two integers , denoting the number of given integers and the given parameter.

The second line contains n integers , denoting the given integers.

输出描述

Output one line containing one integer, denoting the maximum number of the integers you can choose.

示例1

输入:

11 2
3 1 4 1 5 9 2 6 5 3 5

输出:

4

说明:

One possible scheme is to choose \{A_3 = 4, A_6 = 9, A_7 = 2, A_8 = 6\}.

原站题解

上次编辑到这里,代码来自缓存 点击恢复默认模板

C++(g++ 7.5.0) 解法, 执行用时: 55ms, 内存消耗: 812K, 提交时间: 2022-10-31 13:16:12

#include<bits/stdc++.h>
using namespace std;
int main()
{
	int n,k;
	cin>>n>>k;
	int a[100005];
	for(int i=1;i<=n;i++)
	{
		cin>>a[i];
	}
	sort(a+1,a+1+n);
	int p=a[1]+k;
	int s=1;
	for(int i=2;i<=n;i++)
	{
		if(p<=a[i])
		{
			p=a[i]+k;
			s++;
		}
	}
	cout<<s;
} 

C++ 解法, 执行用时: 20ms, 内存消耗: 784K, 提交时间: 2021-12-01 13:17:05

#include<bits/stdc++.h>
using namespace std;
const int N=1e5+5;
int a[N];
int main(){
	int n,k,s=-1e9,ans=0;
	cin>>n>>k;
	for(int i=1;i<=n;i++) scanf("%d",&a[i]);
	sort(a+1,a+n+1);
	for(int i=1;i<=n;i++) if(a[i]-s>=k) ans++,s=a[i];
	cout<<ans;
}

Python3 解法, 执行用时: 159ms, 内存消耗: 17756K, 提交时间: 2023-08-03 22:18:17

n,k=map(int,input().split())
a=list(map(int,input().split()))
a.sort()
t=a[0]
ans=1
for i in range(1,n):
    if a[i]-t>=k:
        ans+=1
        t=a[i]
print(ans)

上一题