You are a coach at your local university. There are n n n students under your supervision, the programming skill of the i i i-th student is a i a_i ai.
You have to create a team for a new programming competition. As you know, the more students some team has the more probable its victory is! So you have to create a team with the maximum number of students. But you also know that a team should be balanced. It means that the programming skill of each pair of students in a created team should differ by no more than 5.
Your task is to report the maximum possible number of students in a balanced team.
Input
The first line of the input contains one integer
n
(
1
≤
n
≤
2
⋅
1
0
5
)
n (1 \leq n \leq 2⋅10^5)
n(1≤n≤2⋅105) — the number of students.
The second line of the input contains n n n integers a 1 , a 2 , … , a n ( 1 ≤ a i ≤ 1 0 9 ) a_1,a_2,…,a_n (1 \leq a_i \leq 10^9) a1,a2,…,an(1≤ai≤109), where a i a_i ai is a programming skill of the i i i-th student.
Output
Print one integer — the maximum possible number of students in a balanced team.
Examples
input |
---|
6 |
1 10 17 12 15 2 |
output |
3 |
input |
---|
10 |
1337 1337 1337 1337 1337 1337 1337 1337 1337 1337 |
output |
10 |
input |
---|
6 |
1 1000 10000 10 100 1000000000 |
output |
1 |
Note
In the first example you can create a team with skills [12,17,15].
In the second example you can take all students in a team because their programming skills are equal.
In the third example you can create a team consisting of a single student (and you cannot create a team consisting of at least two students).
题目大意
有 n n n个学生,每个学生都有一个能力值 a i a_i ai,在 n n n个学生中选 k k k个学生,使得 k k k个学生中能力最大值与最小值的差不超过 5 5 5,问 k k k的最大值。
解题思路
首先,读完这道题目之后第一反应肯定是先对能力值进行一个排序,然后呢?思考一个问题就是对于某一个点 i i i,它到底与那个点进行作差比较?所以我就另外开一个数组来记录一下每一个点满足 k k k最大的对应选择中最小值的下标值,每一次比较就可以找到下标值存的值进行比较。
AC代码
#include<bits/stdc++.h>
const int Max_N=2e5+6;
using namespace std;
int a[Max_N];
int dp[Max_N];
bool cmp(int a,int b)
{
return a<b;
}
int main()
{
int n;
cin>>n;
for(int i=1;i<=n;i++)
{
cin>>a[i];
}
sort(a+1,a+n+1,cmp);
int res=0,ans=1;
dp[1]=1;
for(int i=2;i<=n;i++)
{
if(a[i]-a[dp[i-1]]<=5)
{
dp[i]=dp[i-1];
ans++;
}
else
{//不满足条件进行更新
res=max(res,ans);
for(int j=dp[i-1]+1;j<=i;j++)
{
if(a[i]-a[j]<=5)
{
dp[i]=j;
ans=ans-(j-dp[i-1])+1;
break;
}
}
}
}
res=max(res,ans);
cout<<res<<endl;
}
总结
看完题目,理解求什么,把问题简单化,逐个击破。