解法一:动态规划

自己没想出来。。。
参见官方题解:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/solution/mai-mai-gu-piao-de-zui-jia-shi-ji-han-shou-xu-fei-/

  1. class Solution {
  2. public int maxProfit(int[] prices, int fee) {
  3. // last保存上一次状态, cur保存当前状态
  4. // 持有股票状态下的最大利润
  5. int lastHold = -prices[0];
  6. // 不持有股票状态下的最大利润
  7. int lastCash = 0;
  8. int curHold = lastHold;
  9. int curCash = lastCash;
  10. for (int i = 1; i < prices.length; ++i) {
  11. curCash = Math.max(lastCash, lastHold + prices[i] - fee);
  12. curHold = Math.max(lastHold, lastCash - prices[i]);
  13. lastCash = curCash;
  14. lastHold = curHold;
  15. }
  16. return Math.max(curHold, curCash);
  17. }
  18. }