用upper_bound求解
#include<iostream>
#include<algorithm>
using namespace std;
const int maxn = 1e5 + 10;
typedef long long LL;
LL n, a[maxn], p;
int main()
{
scanf("%lld%lld", &n, &p);
for (int i = 0; i < n; i++)scanf("%lld", &a[i]);
sort(a, a + n);
int maxnum = 0;
for (int i = 0; i < n; i++)
{
int m = upper_bound(a + i + 1, a + n, a[i] * p) - a;
maxnum = max(maxnum, m - i);
}
printf("%lld", maxnum);
return 0;
}
two pointers:i和j都从0开始遍历(不是一个头一个尾),这样一次遍历就可以
#include<iostream>
#include<algorithm>
using namespace std;
const int maxn = 1e5 + 10;
typedef long long LL;
LL n, a[maxn], p;
int main()
{
scanf("%lld%lld", &n, &p);
for (int i = 0; i < n; i++)scanf("%lld", &a[i]);
sort(a, a + n);
LL maxnum = 0;
LL i = 0, j = 0;
while (i < n&&j<n)
{
LL number = a[i] * p;
while (a[j] <= number&&j<n)j++;
maxnum = max(maxnum, j - i);
i++;
}
printf("%lld", maxnum);
return 0;
}