跳至主要內容

714. Best Time to Buy and Sell Stock with Transaction Fee


714. Best Time to Buy and Sell Stock with Transaction Feeopen in new window

🟠   🔖  贪心 数组  🔗 LeetCodeopen in new window

题目

You are given an array prices where prices[i] is the price of a given stock on the ith day, and an integer fee representing a transaction fee.

Find the maximum profit you can achieve. You may complete as many transactions as you like, but you need to pay the transaction fee for each transaction.

Note:

  • You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
  • The transaction fee is only charged once for each stock purchase and sale.

Example 1:

Input: prices = [1,3,2,8,4,9], fee = 2

Output: 8

Explanation: The maximum profit can be achieved by:

  • Buying at prices[0] = 1
  • Selling at prices[3] = 8
  • Buying at prices[4] = 4
  • Selling at prices[5] = 9

The total profit is ((8 - 1) - 2) + ((9 - 4) - 2) = 8.

Example 2:

Input: prices = [1,3,7,5,10,3], fee = 3

Output: 6

Constraints:

  • 1 <= prices.length <= 5 * 10^4
  • 1 <= prices[i] < 5 * 10^4
  • 0 <= fee < 5 * 10^4

题目大意

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

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

返回获得利润的最大值。

注意:这里的一笔交易指买入持有并卖出股票的整个过程,每笔交易你只需要为支付一次手续费。

示例 1:

输入: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

示例 2:

输入:prices = [1,3,7,5,10,3], fee = 3

输出:6

解题思路

  1. 动态规划: 定义一个二维数组 dp,其中 dp[i][0] 表示第 i 天不持有股票时的最大利润, dp[i][1] 表示第 i 天持有股票时的最大利润。

  2. 状态转移方程:

    • dp[i][0] = max(dp[i-1][0], dp[i-1][1] + prices[i] - fee),表示在第 i 天,不持有股票的最大利润等于前一天不持有股票的最大利润,或者前一天持有股票的最大利润 加上今天卖出的利润 减去手续费的最大值。
    • dp[i][1] = max(dp[i-1][1], dp[i-2][0] - prices[i]),表示在第 i 天,持有股票的最大利润等于前一天持有股票的最大利润,或者之前两天不持有股票的最大利润减去今天买入的利润的最大值。
  3. 边界条件:

    • 第一天(i == 0)时,dp[0][0] = 0dp[0][1] = -prices[0]
  4. 初始化: 初始化利润为 0。

  5. 返回最大利润: 最后返回 dp[n - 1][0],即最后一天不持有股票的最大利润,因为若最后一天还持有股票没有卖出,收益肯定小于做了一次交易的情况。

  • 时间复杂度: O(n) - 遍历整个二维数组,其中 n 是股票价格数组的长度。
  • 空间复杂度: O(n) - 使用了一个 2 * n 的二维数组来存储中间状态。

代码

/**
 * @param {number[]} prices
 * @param {number} fee
 * @return {number}
 */
var maxProfit = function (prices, fee) {
	const n = prices.length;
	const dp = new Array(n).fill(0).map(() => new Array(2).fill(0));
	for (let i in prices) {
		if (i == 0) {
			dp[0][0] = 0;
			dp[0][1] = -prices[0];
			continue;
		}
		dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1] + prices[i] - fee);
		dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][0] - prices[i]);
	}
	return dp[n - 1][0];
};

相关题目

相关题目
- [122. 买卖股票的最佳时机 II](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii)