目录
学习目标
学习内容
121. 买卖股票的最佳时机
122.买卖股票的最佳时机II
学习目标
- 121. 买卖股票的最佳时机
- 122.买卖股票的最佳时机II
学习内容
121. 买卖股票的最佳时机
121. 买卖股票的最佳时机 - 力扣(LeetCode)https://leetcode.cn/problems/best-time-to-buy-and-sell-stock/
class Solution:
def maxProfit(self, prices: List[int]) -> int:
n = len(prices)
dp = [[0]*n for _ in range(2)]
dp[0][0]=-prices[0]
for i in range(1,n):
dp[0][i]=max(-prices[i],dp[0][i-1])
dp[1][i]=max(dp[0][i-1]+prices[i],dp[1][i-1])
print(dp)
return dp[1][-1]
class Solution:
def maxProfit(self, prices: List[int]) -> int:
n = len(prices)
a = -prices[0]
b = 0
for i in range(1,n):
a = max(-prices[i],a)
b = max(a+prices[i],b)
return b
122.买卖股票的最佳时机II
122. 买卖股票的最佳时机 II - 力扣(LeetCode)https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-ii/
class Solution:
def maxProfit(self, prices: List[int]) -> int:
n = len(prices)
dp = [[0]*n for _ in range(2)]
dp[0][0] = -prices[0]
for i in range(1,n):
dp[0][i] = max(dp[0][i-1],dp[1][i-1]-prices[i])
dp[1][i] = max(dp[1][i-1],dp[0][i-1]+prices[i])
return dp[1][-1]
class Solution:
def maxProfit(self, prices: List[int]) -> int:
n = len(prices)
a = -prices[0]
b = 0
for i in range(1,n):
a = max(a,b-prices[i])
b = max(b,a+prices[i])
return b