1833. Maximum Ice Cream bars

刷题日记

1833. Maximum Ice Cream bars

It is a sweltering summer day, and a boy wants to buy some ice cream bars.

At the store, there are n ice cream bars. You are given an array costs of length n, where costs[i] is the price of the ith ice cream bar in coins. The boy initially has coins coins to spend, and he wants to buy as many ice cream bars as possible.

Return the maximum number of ice cream bars the boy can buy with coins coins.

Note: The boy can buy the ice cream bars in any order.

思路

完成任务需要的几个步骤

  1. 将获得的costs数组进行从小到大排序;
  2. 对排序后数组进行遍历的同时,判断所剩coins与总价格之间的大小关系;

代码实现

class Solution {
    public int maxIceCream(int[] costs, int coins) {
        Arrays.sort(costs);
        for(int i = 0; i < costs.length; i++) {
            if((coins -= costs[i]) < 0){
                return i;
            }
        }
        return costs.length;
    }
}

第一种实现风格,是我最终采用的风格,非常精炼,直接在if中包含了对coins的减法运算和结果的判断,同时减法和判断很直观。

public int maxIceCream(int[] costs, int coins) {
        Arrays.sort(costs);
        int res = 0;
        for (int i : costs) {
            if (coins >= i) {
                res++;
                coins -= i;
            }
        }
        return res;
    }

第二种实现风格,判断思路是对比每一次剩下的钱和当前ice cream bar的价格,但这种风格的缺点在于没有提前中止,即最终要把整个数组遍历一遍,时间消耗更大。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值