算法: 买卖股票的最佳时机 IV 188. Best Time to Buy and Sell Stock IV
Posted AI架构师易筋
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了算法: 买卖股票的最佳时机 IV 188. Best Time to Buy and Sell Stock IV相关的知识,希望对你有一定的参考价值。
188. Best Time to Buy and Sell Stock IV
You are given an integer array prices where prices[i] is the price of a given stock on the ith day, and an integer k.
Find the maximum profit you can achieve. You may complete at most k transactions.
Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
Example 1:
Input: k = 2, prices = [2,4,1]
Output: 2
Explanation: Buy on day 1 (price = 2) and sell on day 2 (price = 4), profit = 4-2 = 2.
Example 2:
Input: k = 2, prices = [3,2,6,5,0,3]
Output: 7
Explanation: Buy on day 2 (price = 2) and sell on day 3 (price = 6), profit = 6-2 = 4. Then buy on day 5 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.
Constraints:
0 <= k <= 100
0 <= prices.length <= 1000
0 <= prices[i] <= 1000
动态规划解法
这是 O(kn),显然不是最优的。我将关键变量命名为局部利润和全局利润,以使事情更容易理解. 处理分了3部分
- 如果n少于2次交易,
return 0
- 如果交易次数k >= n /2, 所以只要现在大于上一次,就做交易,累计和即可。
- 当前的k层的交易
max(profit, 0)
,加上k-1层交易的最大收益,则为当前的要是做交易最大收益;跟当前层放弃这次交易的最大收益做对比。
class Solution:
def maxProfit(self, k: int, prices: List[int]) -> int:
n = len(prices)
if n < 2:
return 0
# k is big enougth to cover all ramps.
if k >= n / 2:
return sum(i - j for i, j in zip(prices[1:], prices[:-1]) if i - j > 0)
globalMax = [[0] * n for _ in range(k+1)]
for r in range(1, k+1):
localMax = [0] * n
for c in range(1, n):
profit = prices[c] - prices[c - 1]
localMax[c] = max(
# We have made max profit with (r - 1) transations in (c - 1) days.
# 1. For the last transation, we buy stock on day (c - 1) and sell it on day j.
# 2. For the last transation, we buy stock on day c and
# sell it on the same day, so we have 0 profit, apparently we do not have to add it.
globalMax[r-1][c-1] + max(profit, 0),
# We have made profit in (c - 1) days.
# We want to cancel the day (c - 1) sale and sell it on day c.
localMax[c-1] + profit
)
globalMax[r][c] = max(globalMax[r][c-1], localMax[c])
return globalMax[k][-1
]
以上是关于算法: 买卖股票的最佳时机 IV 188. Best Time to Buy and Sell Stock IV的主要内容,如果未能解决你的问题,请参考以下文章
算法: 买卖股票的最佳时机 IV 188. Best Time to Buy and Sell Stock IV
Leetcode No.188 买卖股票的最佳时机 IV(动态规划)