算法 第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
		
相关推荐
Savior`L4 小时前
二分算法及常见用法
数据结构·c++·算法
mmz12074 小时前
前缀和问题(c++)
c++·算法·图论
努力学算法的蒟蒻5 小时前
day27(12.7)——leetcode面试经典150
算法·leetcode·面试
甄心爱学习6 小时前
CSP认证 备考(python)
数据结构·python·算法·动态规划
kyle~6 小时前
排序---常用排序算法汇总
数据结构·算法·排序算法
AndrewHZ6 小时前
【遥感图像入门】DEM数据处理核心算法与Python实操指南
图像处理·python·算法·dem·高程数据·遥感图像·差值算法
CoderYanger6 小时前
动态规划算法-子序列问题(数组中不连续的一段):28.摆动序列
java·算法·leetcode·动态规划·1024程序员节
有时间要学习7 小时前
面试150——第二周
数据结构·算法·leetcode
liu****7 小时前
3.链表讲解
c语言·开发语言·数据结构·算法·链表