结束了打家劫舍问题,之前在练习贪心算法的时候做过LC122,现在用动态规划做一下LC121 和122。
121. Best Time to Buy and Sell Stock
You are given an array
priceswhereprices[i]is the price of a given stock on theithday.You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.
Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return
0.
这道题毫无疑问可以用贪心的方法解出来,不过既然练习到动态规划,当然是要应用动态规划五部曲了。
- class Solution:
- def maxProfit(self, prices: List[int]) -> int:
- length = len(prices)
- if len == 0:
- return 0
- dp = [[0] * 2 for _ in range(length)]
- dp[0][0] = -prices[0]
- dp[0][1] = 0
- for i in range(1, length):
- dp[i][0] = max(dp[i-1][0], -prices[i])
- dp[i][1] = max(dp[i-1][1], prices[i] + dp[i-1][0])
- return dp[-1][1]
122. Best Time to Buy and Sell Stock II
You are given an integer array
priceswhereprices[i]is the price of a given stock on theithday.On each day, you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However, you can buy it then immediately sell it on the same day.
Find and return the maximum profit you can achieve.
和上一题的区别是,股票可以买卖多次了
因此在递推公式这一步,会和前面有区别。
所以买入股票的时候,可能会有之前买卖的利润即:dp[i - 1][1],所以dp[i - 1][1] - prices[i]。
- class Solution:
- def maxProfit(self, prices: List[int]) -> int:
- length = len(prices)
- dp = [[0] * 2 for _ in range(length)]
- dp[0][0] = -prices[0]
- dp[0][1] = 0
- for i in range(1, length):
- dp[i][0] = max(dp[i-1][0], dp[i-1][1] - prices[i])
- dp[i][1] = max(dp[i-1][1], dp[i-1][0] + prices[i])
- return dp[-1][1]