📌  相关文章
📜  以交易费买卖股票后的最大利润| 2套(1)

📅  最后修改于: 2023-12-03 14:49:30.983000             🧑  作者: Mango

以交易费买卖股票后的最大利润 | 2套

题目描述

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

卖出股票时,需要支付给定的交易费用,注意可以交易任意次数,但是每次买入股票需要支付交易费用。

求买卖股票所能获得的最大利润。

示例

输入: prices = [1, 3, 2, 8, 4, 9], fee = 2 输出: 8 解释: 能够达到的最大利润为 8, 在第 2 天买入(价格 = 3)并在第 4 天卖出(价格 = 8), 此时利润为 8 - 3 - 2 = 3。

解题思路

我们可以用动态规划来解决此题。需要用两个变量 buysell 来表示手上持有股票和手上不持有股票时能获取的最大利润。

对于第 i 天,如果手上持有股票,可能来自于前一天手上持有股票或者今天买入股票(需要花费 prices[i] + fee 的价格):

buy = max(buy, sell - prices[i] - fee)

如果手上不持有股票,可能来自于前一天手上不持有股票或者今天卖出股票(可以获利 prices[i]):

sell = max(sell, buy + prices[i])

最后返回 sell 即为最大利润。

代码实现

Python3 代码:

from typing import List

class Solution:
    def maxProfit(self, prices: List[int], fee: int) -> int:
        buy, sell = -float('inf'), 0
        for price in prices:
            buy = max(buy, sell - price - fee)
            sell = max(sell, buy + price)
        return sell

Java 代码:

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

C++ 代码:

class Solution {
public:
    int maxProfit(vector<int>& prices, int fee) {
        int buy = -prices[0] - fee, sell = 0;
        for (auto price : prices) {
            int newBuy = max(buy, sell - price - fee);
            int newSell = max(sell, buy + price);
            buy = newBuy;
            sell = newSell;
        }
        return sell;
    }
};
时间复杂度

时间复杂度为 $O(n)$,其中 $n$ 为输入数组 prices 的长度。

空间复杂度

空间复杂度为 $O(1)$,只需要用到常数个变量。