任意门
JB loves candy very much.
One day, he finds a candy machine with N candies in it. After reading the instructions of the machine, he knows that he can choose a subset of the N candies. Each candy has a sweet value. After JB chooses the subset, suppose the average sweet value of the chosen candies is X, all the candies with sweet value strictly larger than X will belong to JB. After JB makes the choice, the machine will disappear, so JB only has one opportunity to make a choice.
JB doesn’t care how sweet the candies are, so he just wants to make a choice to maximize the number of candies he will get. JB has been fascinated by candy and can’t think, so he needs you to help him.
Input
The first line contains one integer N (1≤N≤106), denoting the number of candies in the machine.
The second line contains N integers a1,a2,…,aN (1≤ai≤109), denoting the sweet values of the candies.
Output
One integer, denoting the maximum number of candies JB can get.
Example
input
5
1 2 3 4 5
output
2
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N = 1e6+10;
LL n;
LL a[N];
// 小数会拉低平均值
// 只可能因为大数导致获取的糖果数量少
// 默认选取所有的糖果,往下逐步推翻前面的结果
LL get_ans(int l, int r, LL sum)
{
// 找到第一个小于//这里也可以用upper_bound来写
int len = r-l+1;
LL res = 0;
int ll = l, rr = r;
while(ll < rr)
{
int mid = ll + rr >> 1;
if(sum < a[mid]*len)
{
rr = mid;
}
else {
ll = mid+1;
}
}
if(sum < a[ll]*len) return r - ll + 1;
return 0;
}
int main()
{
scanf("%lld", &n);
LL sum = 0;
for(LL i = 1; i <= n; i++)
{
scanf("%lld", &a[i]);
sum += a[i];
}
// 对数据从小到大排序
sort(a+1, a+n+1);
// 默认添加所有元素
LL ans = get_ans(1, n, sum);
for(int i = n; i > 0; i--)
{
sum -= a[i];
ans = max(ans, get_ans(1, i-1, sum));
}
printf("%lld", ans);
}