1833. Maximum Ice Cream bars

阅读: 评论:0

1833. Maximum Ice Cream bars

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的价格,但这种风格的缺点在于没有提前中止,即最终要把整个数组遍历一遍,时间消耗更大。

本文发布于:2024-02-05 05:08:56,感谢您对本站的认可!

本文链接:https://www.4u4v.net/it/170724870563316.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:Maximum   Ice   bars   Cream
留言与评论(共有 0 条评论)
   
验证码:

Copyright ©2019-2022 Comsenz Inc.Powered by ©

网站地图1 网站地图2 网站地图3 网站地图4 网站地图5 网站地图6 网站地图7 网站地图8 网站地图9 网站地图10 网站地图11 网站地图12 网站地图13 网站地图14 网站地图15 网站地图16 网站地图17 网站地图18 网站地图19 网站地图20 网站地图21 网站地图22/a> 网站地图23