題目簡(jiǎn)介
122. 買賣股票的最佳時(shí)機(jī) II
給你一個(gè)整數(shù)數(shù)組 prices ,其中 prices[i] 表示某支股票第 i 天的價(jià)格。
在每一天,你可以決定是否購(gòu)買和/或出售股票。你在任何時(shí)候 最多 只能持有 一股 股票。你也可以先購(gòu)買,然后在 同一天 出售。
返回 你能獲得的 最大 利潤(rùn) 。
55. 跳躍游戲
給你一個(gè)非負(fù)整數(shù)數(shù)組 nums ,你最初位于數(shù)組的 第一個(gè)下標(biāo) 。數(shù)組中的每個(gè)元素代表你在該位置可以跳躍的最大長(zhǎng)度。
判斷你是否能夠到達(dá)最后一個(gè)下標(biāo),如果可以,返回 true ;否則,返回 false 。
45. 跳躍游戲 II
給定一個(gè)長(zhǎng)度為 n 的 0 索引整數(shù)數(shù)組 nums。初始位置為 nums[0]。
每個(gè)元素 nums[i] 表示從索引 i 向前跳轉(zhuǎn)的最大長(zhǎng)度。換句話說(shuō),如果你在 nums[i] 處,你可以跳轉(zhuǎn)到任意 nums[i + j] 處:
0 <= j <= nums[i]
i + j < n
返回到達(dá) nums[n - 1] 的最小跳躍次數(shù)。生成的測(cè)試用例可以到達(dá) nums[n - 1]。
初見思路
122.貪心就好,只要能賺錢就賣出,這樣的話算出最大利潤(rùn)即可。
class Solution:
def maxProfit(self, prices: List[int]) -> int:
if len(prices) <=1:
return 0
max_profit = 0
for i in range(0,len(prices)-1):
if prices[i+1] > prices[i]:
max_profit += prices[i+1] - prices[i]
return max_profit
- 本題的核心在于右側(cè)的貪心的最大邊界是動(dòng)態(tài)的。用一個(gè)臨時(shí)變量把右側(cè)的最大能達(dá)到的位置限定起來(lái),然后再做貪心。
class Solution:
def canJump(self, nums: List[int]) -> bool:
right_index = 0
for i in range(len(nums)):
if i <= right_index:
right_index = max(i + nums[i], right_index)
if right_index >= len(nums) - 1:
return True
return False
45.沿襲55題的思路,只不過(guò)這次考慮走到最后一位的最小步數(shù)。這時(shí)我們要考慮,步數(shù)最少那么每次步幅最大,限定最右邊為每次最大到達(dá)位置,當(dāng)遍歷指針到達(dá)該位置,說(shuō)明走了一步,步數(shù)+1,按照這個(gè)邏輯,我們得到:
class Solution:
def jump(self, nums: List[int]) -> int:
right,max_loc,steps = 0,0,0
for i in range(len(nums)-1):
max_loc = max(max_loc,nums[i]+i)
if i == right:
right = max_loc
steps += 1
return steps
復(fù)盤思路
https://programmercarl.com/0055.%E8%B7%B3%E8%B7%83%E6%B8%B8%E6%88%8F.html
https://programmercarl.com/0045.%E8%B7%B3%E8%B7%83%E6%B8%B8%E6%88%8FII.html