Candy Machine--前缀和&&二分查找

任意门

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);
 
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值