总结
本次训练的是贪心算法相关习题
53题给出了如何求去当前覆盖面积和下一步覆盖面积的解答
122. 买卖股票的最佳时机 II
题目链接:
自己想
1.求出所有单调递增序列和即可,在coding时候借鉴了摆动序列(leecode-摆动序列)的思想,但感觉自己在判断边界条件时候写的有点繁琐?
看完题解
1.简单到可怕,只需要累积求和即可。
完整代码
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
prediff = 0
curdiff = 0
buy = []
make = []
result = 0
for i in range(0,len(prices) - 1):
curdiff = prices[i+1] - prices[i]
if prediff <= 0 and curdiff > 0:
buy.append(prices[i])
prediff = curdiff
elif prediff >= 0 and curdiff < 0 and buy:
make.append(prices[i])
prediff = curdiff
if len(buy) == 0:
if (prices[-1] - prices[0]) > 0:
result = prices[-1] - prices[0]
else:
result = 0
elif len(buy) >= len(make):
if prices[-1] > buy[-1]:
make.append(prices[-1])
temp = min(len(buy),len(make))
for j in range(0,temp):
result += make[j] - buy[j]
print(buy)
print(make)
return result
55. 跳跃游戏
题目链接:
自己想
1.每次跳最大步数,看是否最大步数为下标的值之和可以覆盖全部数组长度-1
但是我的判断条件没有解决:[2,5,0,0] 这个问题!!!
错误代码
class Solution(object):
def canJump(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
i = 0
count = 0
if len(nums) == 1:
return True
while i < len(nums):
a = nums[i]
count += a
if count >= len(nums) - 1:
return True
elif a == 0:
return False
else:
i = a + i
return False
看完题解
1.贪心算法局部最优解:每次取最大跳跃步数(取最大覆盖范围),整体最优解:最后得到整体最大覆盖范围,看是否能到终点.
完整代码
class Solution(object):
def canJump(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
i = 0
cover = 0
if len(nums) == 1:
return True
while i <= cover:
cover = max(i+nums[i],cover)
if cover >= len(nums) - 1:
return True
i += 1
return False
45. 跳跃游戏 II
题目链接:
自己想
看完题解
这里需要统计两个覆盖范围,当前这一步的最大覆盖和下一步最大覆盖,我一直在想如何能很好的记录本次最大覆盖面面积和下次最大覆盖面积,该题的想法给出了很好的解释
完整代码
class Solution(object):
def jump(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
cur_distance = 0
next_distance = 0
ans = 0
if len(nums) == 1:
return 0
for i in range(len(nums)):
next_distance = max(i + nums[i],next_distance)
if i == cur_distance:
ans += 1
cur_distance = next_distance
if next_distance >= len(nums) - 1:
break
return ans
题目链接:
自己想
看完题解
完整代码
在这里插入代码片