当前位置:网站首页>leetcode-1833. 雪糕的最大数量(排序+贪心)
leetcode-1833. 雪糕的最大数量(排序+贪心)
2022-07-31 05:10:00 【lin钟一】

题目链接:https://leetcode.cn/problems/maximum-ice-cream-bars/
思路
直观想法
在给定的硬币情况下,花最小的钱,买最多的雪糕,一眼贪心。
吐槽一句:这题mid难度有点离谱,easy题差不多,经典贪心题
算法
- 对原雪糕价格 costs 数组进行小到大排序
- 遍历 costs 数组,当前的雪糕价格不超过硬币数,则购买,直接减去当前雪糕价格,不用关心怎么搭配买最多,只管当前他最便宜我就买,贪心!
代码示例
func maxIceCream(costs []int, coins int) (ans int) {
//go自带的排序x
sort.Ints(costs)
for i := range costs{
if coins - costs[i] < 0{
break
}
coins -= costs[i]
ans++
}
return
}

复杂度分析
- 时间复杂度:O(n logn) 其中n 是数组 costs 的长度,对数组排序所需要的时间是O(n logn),遍历数组需要O(n)的时间,以上时间取最长则是O(n logn)
- 空间复杂度:O(logn),其中 nn 是数组 costs 的长度。空间复杂度主要取决于排序使用的额外空间。
边栏推荐
- Object Detection Study Notes
- 剑指offer基础版 --- 第24天
- 【C语言趣味小游戏——猜数字】
- If the account number or password is entered incorrectly for many times, the account will be banned.
- Flask 的初识
- wpf wrapPanel居中并从左到右排列
- C语言教程(二)-printf及c自带的数据类型
- 关于小白安装nodejs遇到的问题(npm WARN config global `--global`, `--local` are deprecated. Use `--location=glob)
- Why use Flink and how to get started with Flink?
- Simple command of mysql
猜你喜欢
![[MQ I can speak for an hour]](/img/ef/863c994ac3a7de157bd39545218558.jpg)
[MQ I can speak for an hour]

剑指offer基础版 ---- 第29天
![[Introduction to MySQL 8 to Mastery] Basics - silent installation of MySQL on Linux system, cross-version upgrade](/img/af/7a2cdcc6535c04c508c9ddf9ee0cb2.png)
[Introduction to MySQL 8 to Mastery] Basics - silent installation of MySQL on Linux system, cross-version upgrade

面试官:生成订单30分钟未支付,则自动取消,该怎么实现?

04 【计算属性 侦听属性】

Lock wait timeout exceeded解决方案

Redis进阶 - 缓存问题:一致性、穿击、穿透、雪崩、污染等.

剑指offer基础版 --- 第22天

Distributed transaction processing solution big PK!

关于小白安装nodejs遇到的问题(npm WARN config global `--global`, `--local` are deprecated. Use `--location=glob)
随机推荐
Redis first meeting
数据库上机实验1 数据库定义语言
The TOKEN value of Kubernetes joining the cluster expires
uni-app进阶之内嵌应用【day14】
Simple command of mysql
剑指offer专项突击版 ---- 第 6 天
07 【内置指令 自定义指令】
闭包(五)----一个常见的循环
Input length must be multiple of 8 when decrypting with padded cipher
第7章 网络层第2次练习题答案(第三版)
Quickly master concurrent programming --- the basics
C语言实验五 循环结构程序设计(二)
对list集合进行分页,并将数据显示在页面中
C语言指针详解
1D, 2D, 3D convolution operations in pytorch
剑指offer基础版 ----- 第28天
剑指offer基础版 --- 第21天
快速掌握并发编程 --- 基础篇
tf.keras.utils.pad_sequences()
第7章 网络层第1次练习题答案(第三版)