当前位置: 首页> 健康> 美食 > 代码随想录算法训练营day35 | 122.买卖股票的最佳时机II、55. 跳跃游戏、45.跳跃游戏II

代码随想录算法训练营day35 | 122.买卖股票的最佳时机II、55. 跳跃游戏、45.跳跃游戏II

时间:2025/7/9 16:34:29来源:https://blog.csdn.net/sunflowers11/article/details/139237520 浏览次数:0次

122.买卖股票的最佳时机II

完全想不出来贪心的解法,分解为每天的利润,所有正利润之和为最大利润

class Solution:def maxProfit(self, prices: List[int]) -> int:result = 0for i in range(1, len(prices)):result += max(prices[i] - prices[i-1], 0)return result

55. 跳跃游戏

class Solution:def canJump(self, nums: List[int]) -> bool:maxIndex = 0for i in range(len(nums)):maxIndex = max(maxIndex, i+nums[i])if maxIndex <= i and i != len(nums) - 1:return Falsereturn True

可以不用遍历完成,只要maxIndex能覆盖到终点就行

class Solution:def canJump(self, nums: List[int]) -> bool:maxIndex = 0i = 0while i <= maxIndex:maxIndex = max(maxIndex, i+nums[i])if maxIndex >= len(nums) - 1:return Truei += 1return False

45.跳跃游戏II

贪心的思路,局部最优:当前可移动距离尽可能多走,如果还没到终点,步数再加一。整体最优:一步尽可能多走,从而达到最少步数。

class Solution:def jump(self, nums: List[int]) -> int:if len(nums) <= 1:return 0curDistance = 0nextDistance = 0result = 0for i in range(len(nums)):nextDistance = max(nextDistance, nums[i] + i)if i == curDistance:result += 1curDistance = nextDistanceif nextDistance >= len(nums) - 1:breakreturn result

关键字:代码随想录算法训练营day35 | 122.买卖股票的最佳时机II、55. 跳跃游戏、45.跳跃游戏II

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: