力扣Hot100贪心算法详解及Python实现版本
一、121. 买卖股票的最佳时机
class Solution:
def maxProfit(self, prices):
ans = 0
min_price = prices[0]
for p in prices:
ans = max(ans, p-min_price)
min_price =min(min_price, p)
return ans
二、55. 跳跃游戏
维护一个idx + 距离 = 当前能到的最大位置表即可。
class Solution:
def canJump(self, nums: List[int]) -> bool:
max_idx = 0
for idx, num in enumerate(nums):
if idx > max_idx:
return False
max_idx = max(max_idx, idx+num)
if max_idx < idx:
return False
else:
return True
三、45. 跳跃游戏 II
class Solution:
def jump(self, nums: List[int]) -> int:
ans = 0
max_right = 0
next_right = 0
for i in range(len(nums)-1):
next_right = max(next_right, i+nums[i]) # 下一次跳跃能到的最大位置
if i==max_right: # 走到上次的最大位置了
max_right = next_right # 跳到上次最大位置
ans += 1
return ans
四、763. 划分字母区间
class Solution:
def partitionLabels(self, s: str) -> List[int]:
last = {c: i for i, c in enumerate(s)} # 每个字母最后出现的下标
ans = []
start = end = 0
for i, c in enumerate(s):
end = max(end, last[c]) # 更新当前区间右端点的最大值
if end == i: # 当前区间合并完毕
ans.append(end - start + 1) # 区间长度加入答案
start = i + 1 # 下一个区间的左端点
return ans
作者:Y1nhl