leetcode 1833. Maximum Ice Cream Bars(最大数量的冰棒)

在这里插入图片描述
数组costs里面是每根冰棒的价格,现手上有coins的钱,问最多能买多少个冰棒。

思路:

最容易想到的就是给价格从小到大排个序,先买便宜的再买贵的,就能保证买的最多。

    public int maxIceCream(int[] costs, int coins) {
        int n = costs.length;
        int res = 0;

        Arrays.sort(costs);

        for(int i = 0; i < n; i++) {
            if(coins < costs[i]) return res;
            coins -= costs[i];
            res ++;
        }
        return res;
    }

上面的方法没问题,但是不是最快的,因为排序要O(nlogn),
有没有办法在O(n)复杂度?

可以看到的是,有相同价格的冰棒,它们可以一起处理。
统计每个价格的冰棒的数量,
把这些数量一起处理掉,就可以避免遍历很长的数组。
先记下最大的价格,然后就在0~最大价格的范围内遍历即可。

    public int maxIceCream(int[] costs, int coins) {
        int n = costs.length;
        int maxCost = Arrays.stream(costs).max().getAsInt();
        int[] cnt = new int[maxCost+1];
        int res = 0;

        for(int cost : costs) {
            cnt[cost] ++;
        }

        for(int cost = 0; cost <= maxCost; cost++) {
            if(cnt[cost] == 0) continue;
            if(coins < cost) return res;
            int cur = Math.min(cnt[cost], coins/cost);
            coins -= cost * cur;
            res += cur;
        }
        return res;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值