算法 第34天 贪心3

1005 K 次取反后最大化的数组和

给你一个整数数组 nums 和一个整数 k ,按以下方法修改该数组:

选择某个下标 i 并将 nums[i] 替换为 -nums[i] 。

重复这个过程恰好 k 次。可以多次选择同一个下标 i 。

以这种方式修改数组后,返回数组 可能的最大和 。

输入:nums = [4,2,3], k = 1

输出:5

python 复制代码
def  largestSumAfterKNegations(A:list,K:int)->int:
	A.sort(key=lambda x :abs(x),reverse=True)
	for i in range(len(A)):
		if A[i]<0 and K>0:
			A[i]*=-1
			K-=1
		if K%2==1:
			A[-1]=-A[-1]
		result=sum(A)
		return result

134 加油站

在一条环路上有 n 个加油站,其中第 i 个加油站有汽油 gas[i] 升。

你有一辆油箱容量无限的的汽车,从第 i 个加油站开往第 i+1 个加油站需要消耗汽油 cost[i] 升。你从其中的一个加油站出发,开始时油箱为空。

给定两个整数数组 gas 和 cost ,如果你可以按顺序绕环路行驶一周,则返回出发时加油站的编号,否则返回 -1 。如果存在解,则 保证 它是 唯一 的。

python 复制代码
# 暴力
def canCompleteCircuit(gas:list,cost:list)->int:
	for i in range(len(cost)):
		rest=gas[i]-cost[i]
		index=(i+1)%len(cost)
		while rest>0 and index!=i:
			rest+=(gas[index]-cost[index])
			index=(i+1)%len(cost)
		if rest>=0 and index==i:
			return i
	return -1

#贪心
def canCompleteCircuit(gas:list,cost:list)->int:
	curSum=0
	totalSum=0
	start=0
	for i in range(len(gas)):
		curSum+=gas[i]-cost[i]
		total+=totalSum+=gas[i]-cost[i]
		if curSum<0:
			start=i+1
			cursum=0
	if totalSum<0:
		return -1
	return start
	
	

135 分发糖果

n 个孩子站成一排。给你一个整数数组 ratings 表示每个孩子的评分。

你需要按照以下要求,给这些孩子分发糖果:

每个孩子至少分配到 1 个糖果。

相邻两个孩子评分更高的孩子会获得更多的糖果。

请你给每个孩子分发糖果,计算并返回需要准备的 最少糖果数目 。

python 复制代码
def candy(ratings:list)->int:
	candyVec=[1]*len(ratings)
	for i in range(1,len(ratings)):
		if ratings[i]>ratings[i-1]:
			candyVec[i]=candyVec[i-1]+1
	for i in range(len(ratings)-1-1,-1,-1):
		if ratings[i]>ratings[i+1]
			candyVec[i]=max(candyVec[i],candy[i+1]+1)
	result=sum(candyVec)
	return result
		
相关推荐
KYGALYX3 小时前
逻辑回归详解
算法·机器学习·逻辑回归
铉铉这波能秀3 小时前
LeetCode Hot100数据结构背景知识之集合(Set)Python2026新版
数据结构·python·算法·leetcode·哈希算法
踢足球09293 小时前
寒假打卡:2026-2-8
数据结构·算法
IT猿手3 小时前
基于强化学习的多算子差分进化路径规划算法QSMODE的机器人路径规划问题研究,提供MATLAB代码
算法·matlab·机器人
千逐-沐风3 小时前
SMU-ACM2026冬训周报3rd
算法
铉铉这波能秀4 小时前
LeetCode Hot100数据结构背景知识之元组(Tuple)Python2026新版
数据结构·python·算法·leetcode·元组·tuple
晚霞的不甘4 小时前
Flutter for OpenHarmony 实现计算几何:Graham Scan 凸包算法的可视化演示
人工智能·算法·flutter·架构·开源·音视频
㓗冽4 小时前
60题之内难题分析
开发语言·c++·算法
大江东去浪淘尽千古风流人物4 小时前
【VLN】VLN仿真与训练三要素 Dataset,Simulators,Benchmarks(2)
深度学习·算法·机器人·概率论·slam
铉铉这波能秀5 小时前
LeetCode Hot100数据结构背景知识之字典(Dictionary)Python2026新版
数据结构·python·算法·leetcode·字典·dictionary