[leetcode]股票买卖问题总结

本文深入解析了LeetCode上的股票买卖问题系列,特别是带有交易费用的情况。通过递归关系详细阐述了如何定义和计算不同交易状态下的最大利润,包括持有股票和不持有股票两种情况。文章还解释了交易次数如何影响策略,并讨论了当交易次数无限时,策略选择的不变性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/discuss/108870/Most-consistent-ways-of-dealing-with-the-series-of-stock-problems

反反复复看了好几遍,终于算是看懂了。总结一下。

Therefore our definition of T[i][k] should really be split into two: T[i][k][0] and T[i][k][1], where the former denotes the maximum profit at the end of the i-th day with at most k transactions and with 0 stock in our hand AFTER taking the action, while the latter denotes the maximum profit at the end of the i-th day with at most k transactions and with 1 stock in our hand AFTER taking the action.
Recurrence relations:
T[i][k][0] = max(T[i-1][k][0], T[i-1][k][1] + prices[i])
T[i][k][1] = max(T[i-1][k][1], T[i-1][k-1][0] - prices[i])

  1. 为什么sell的时候k不-1,buy的时候k-1?
    因为buy和sell是成双成对的,我们这里只假设buy会消耗一次transaction,光sell是不算消耗了一次transaction的。
  2. 为什么k都是跟着sell和buy动作在变,但是0和1不跟着变?
    可以这么理解,0和1是跟随i变化的。我们sell或buy,立刻会影响k,但是stock状态是和第几天有关。
    T[i][k][1] = max(T[i-1][k][1], T[i-1][k-1][0] - prices[i])
    表示i-1天是没有stock的,在此状态下buy了,这一天的k就要减1,但是stock的状态是到下一天才生效。

  1. T[-1][k][0] = 0,
  2. T[-1][k][1] = -Infinity
  3. T[i][0][0] = 0,
  4. T[i][0][1] = -Infinity
  1. 交易不开始,手上也没股票,所以没profit
  2. 交易不开始,手上是不可能有股票的,所以不可能
  3. 不能交易(k=0),手上没股票,所以没profit
  4. 不能交易,手上怎么可能会持股呢,不可能(T[i][0][1]是T[i][-1][0]-price[i]得到的,T[i][-1][0]就不存在,这个解释不知道对不对)

If k is positive infinity, then there isn’t really any difference between k and k - 1 (wonder why? see my comment below), which implies T[i-1][k-1][0] = T[i-1][k][0] and T[i-1][k-1][1] = T[i-1][k][1].

在k是无穷大的时候,k的变化不再影响profit了。因为k大于n/2(n是数组长度),之后的buy和sell都是没有意义的。


(Note: The caching of the old values of T_ik0, that is, the variable T_ik0_old, is unnecessary.

这里还不懂,我感觉加上pre之后更好理解

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值