算法 第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
		
相关推荐
大怪v37 分钟前
前端:人工智能?我也会啊!来个花活,😎😎😎“自动驾驶”整起!
前端·javascript·算法
惯导马工3 小时前
【论文导读】ORB-SLAM3:An Accurate Open-Source Library for Visual, Visual-Inertial and
深度学习·算法
骑自行车的码农4 小时前
【React用到的一些算法】游标和栈
算法·react.js
博笙困了4 小时前
AcWing学习——双指针算法
c++·算法
moonlifesudo5 小时前
322:零钱兑换(三种方法)
算法
NAGNIP1 天前
大模型框架性能优化策略:延迟、吞吐量与成本权衡
算法
美团技术团队1 天前
LongCat-Flash:如何使用 SGLang 部署美团 Agentic 模型
人工智能·算法
Fanxt_Ja1 天前
【LeetCode】算法详解#15 ---环形链表II
数据结构·算法·leetcode·链表
侃侃_天下1 天前
最终的信号类
开发语言·c++·算法
茉莉玫瑰花茶1 天前
算法 --- 字符串
算法