LeetCode309-最佳买卖股票时机含手续费

题目链接

英文链接:https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/

中文链接:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/

题目详述

给定一个整数数组 prices,其中第 i 个元素代表了第 i 天的股票价格 ;非负整数 fee 代表了交易股票的手续费用。

你可以无限次地完成交易,但是你每次交易都需要付手续费。如果你已经购买了一个股票,在卖出它之前你就不能再继续购买股票了。

返回获得利润的最大值。

示例 1:

1
2
3
4
5
6
7
8
输入: prices = [1, 3, 2, 8, 4, 9], fee = 2
输出: 8
解释: 能够达到的最大利润:
在此处买入 prices[0] = 1
在此处卖出 prices[3] = 8
在此处买入 prices[4] = 4
在此处卖出 prices[5] = 9
总利润: ((8 - 1) - 2) + ((9 - 4) - 2) = 8.

注意:

  • 0 < prices.length <= 50000.
  • 0 < prices[i] < 50000.
  • 0 <= fee < 50000.

题目详解

本题在 LeetCode309-最佳买卖股票时机含冷冻期 基础上去掉了冷冻期,改为了含手续费,解题思路是一致的,存在两个有效状态:持有股票和未持有股票,可以运用动态规划来解决。

  • sell[i] 表示第 i 天时未持有股票可获得的最大利润。
  • buy[i] 表示第 i 天时持有股票可获得的最大利润。
  • 对于 sell[i],状态转移方程为 sell[i] = max{sell[i - 1], buy[i - 1] + prices[i] - fee}
  • 对于 buy[i],状态转移方程为 buy[i] = max{buy[i - 1], sell[i - 1]} - prices[i]
  • 最终的结果为最后一天不持有股票的状态,即 sell[n - 1]。
  • 由于当前状态只与上一个状态有关,可以将空间复杂度降为 O(1)。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class LeetCode_00714 {

public int maxProfit(int[] prices, int fee) {
if (prices == null || prices.length <= 1) {
return 0;
}
int sell = 0;
int buy = -prices[0];
for (int i = 1; i < prices.length; ++i) {
sell = Math.max(sell, buy + prices[i] - fee);
buy = Math.max(buy, sell - prices[i]);
}
return sell;
}
}