刷题日记
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.
思路
完成任务需要的几个步骤
- 将获得的costs数组进行从小到大排序;
- 对排序后数组进行遍历的同时,判断所剩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的价格,但这种风格的缺点在于没有提前中止,即最终要把整个数组遍历一遍,时间消耗更大。