122.买卖股票的最佳时机II
class Solution:
def maxProfit(self, prices: List[int]) -> int:
result = 0
for i in range(len(prices) - 1):
count = prices[i+1] - prices[i]
if count > 0:
result += count
return result
方法二:把if条件变成max
class Solution:
def maxProfit(self, prices: List[int]) -> int:
result = 0
for i in range(len(prices) - 1):
count = max(prices[i+1] - prices[i], 0) #这样写也很好
result += count
return result
55. 跳跃游戏
class Solution:
def canJump(self, nums: List[int]) -> bool:
result = 0
if len(nums) == 1:
return True
for i in range(len(nums)):
if i <= result:
count = i + nums[i]
result = max(count, result)
if result >= len(nums) - 1:
return True
return False
【思考】
解题思路:在每个i处看是否能到达最终点。
if i <= result: 这句限制条件很重要!!如果i>result了,说明中途遇到0,且0前面的没有能越过0走到后面的。这一句有点绕,体会。
45.跳跃游戏II
class Solution:
def jump(self, nums):
if len(nums) == 1:
return 0
cur, next = 0, 0
ans = 0
for i in range(len(nums)):
next = max(nums[i] + i, next)
if i == cur:
ans += 1
cur = next
if next >= len(nums) - 1:
break
return ans
这道题没很理解本质,为什么i = =cur时,ans+1