[Python] 贪心算法简单版

贪心算法-简单版

贪心算法的一般使用场景是给定一个列表ls, 让你在使用最少的数据的情况下达到或超过n .

我们就来使用上面讲到的这个朴素的例题来讲讲贪心算法的基本模板:

2-1.排序

既然要用最少的数据, 我们就要优先用大的数据拼 , 为了实现这个效果, 我们得先给列表从大到小排序.

python 复制代码
sorted(ls, reverse = True)
# 别忘了reverse = True从大到小

2-2.选择

我们需要遍历列表, 每次选出现在的元素, 记录当前总和和累加次数, 当总和大于等于n时, 结束循环.

python 复制代码
tot = 0
cnt = 0
# 注意一个很容易错的地方, 这里的语句顺序不可改变!
for l in ls:
	tot += l
	if tot >= n:
		break
	cnt += 1

2-3.完整简单版模板

注释版:

python 复制代码
# 输入
n = int(input())
ls = [int(i) for i in input().split()]

# 排序
sorted(ls, reverse = True)

# 主要算法, 摘大苹果
tot = 0
cnt = 0
for l in ls:
	tot += l
	if tot >= n:
		break
	cnt += 1

记忆版:

python 复制代码
n = int(input())
ls = [int(i) for i in input().split()]
sorted(ls, reverse = True)
tot = 0
cnt = 0
for l in ls:
	tot += l
	if tot >= n:
		break
	cnt += 1
相关推荐
cxr82821 小时前
GPU 加速声场求解器 CUDA Kernel 实现细节 —— 高频超声传播仿真并行计算引擎
人工智能·python·目标跟踪
echome88821 小时前
JavaScript Promise 与 async/await 实战:5 个高频异步编程场景的优雅解决方案
开发语言·javascript·ecmascript
枫叶林FYL21 小时前
第10章 符号推理与神经符号AI
pytorch·python·深度学习
xcLeigh21 小时前
IoTDB Java 原生 API 实战:SessionPool 从入门到精通
java·开发语言·数据库·api·iotdb·sessionpool
杜子不疼.21 小时前
Java 智能体学习避坑指南:3 个常见误区,新手千万别踩,高效少走弯路
java·开发语言·人工智能·学习
冬天vs不冷21 小时前
为什么 Java 不让 Lambda 和匿名内部类修改外部变量?final 与等效 final 的真正意义
android·java·开发语言
星河耀银海21 小时前
JAVA 多线程编程:从基础原理到实战应用
java·开发语言·php
星河耀银海21 小时前
JAVA IO流:从基础原理到实战应用
java·服务器·开发语言
摸鱼仙人~1 天前
Math.js 使用教程
开发语言·javascript·ecmascript
nimadan121 天前
剧本杀app2025推荐,多类型剧本体验与社交互动优势
人工智能·python