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

本文介绍了一种使用动态规划解决股票买卖问题的方法,旨在找到在给定价格数组和交易费用条件下,通过多次交易获取最大利润的策略。文章详细解释了如何定义和更新'sold'和'hold'状态变量,并提供了两种实现方案的Python代码示例。

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

 

714Best Time to Buy and Sell Stock with Transaction Fee

 

题目

 

Your are given an array of integers prices, for which the i-th element is the price of a given stock on day i; and a non-negative integer fee representing a transaction fee.

You may complete as many transactions as you like, but you need to pay the transaction fee for each transaction. You may not buy more than 1 share of a stock at a time (ie. you must sell the stock share before you buy again.)

Return the maximum profit you can make.

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] = 1Selling at prices[3] = 8Buying at prices[4] = 4Selling at prices[5] = 9The total profit is ((8 - 1) - 2) + ((9 - 4) - 2) = 8.

Note:0 < prices.length <= 50000.0 < prices[i] < 50000.0 <= fee < 50000.

分析

给定一个价格数组,第i个元素表示第i天一个给定股票的价格;fee是非负的交易费用,每次交易卖方必须要支付。

本题采用动态规划(Dynamic Programming)的方法,时间复杂度O(N),空间复杂度O(1).

定义两个变量sold和hold:

sold[i] 表示第i天卖掉手中股票所能取得的最大收益,即该天结束后手中不持有股票(保持i-1天不持有的状态/卖掉手中的股票)

hold[i] 表示第i天拥有某个股票时所能获得的最大收益,即该天结束后手中持有股票(保持i-1天持有的状态/买入新股票)

卖出股票时出交易费:

sold[i]=max(sold[i-1], hold[i-1]+p[i]-fee)    #表示取已获得收益与当前卖掉股票的最大值
hold[i]=max(hold[i-1], sold[i-1]-p[i])    #表示取继续持有或买入股票可能获得收益的最大值

买入股票时出交易费:

sold=max(sold,hold+price[i])
hold=max(hold,sold-price[i]-fee)

最后返回遍历完最后一个prices元素之后,手中不持有股票的收益。

完整代码

class Solution(object):
    def maxProfit(self, prices, fee):
        """
        :type prices: List[int]
        :type fee: int
        :rtype: int
        """
        sold,hold=0,-prices[0]  #第0天买入股票,sold为当前收益
        for i in xrange(len(prices)):
            sold = max(sold, hold+prices[i]-fee)    #卖掉股票
            hold = max(hold, sold-prices[i])    #买入股票
        return sold  #输出sold,因为最后一天手中不持有股票

运行速度快于DP max()的方法,采用变量state记录用当前价格卖掉/买入股票所能获得的收益:

    如果state>fee(大于额外的交易费用fee)即可进行交易;如果state<0,当前价格下不进行交易。

class Solution(object):
    def maxProfit(self, prices, fee):
        """
        :type prices: List[int]
        :type fee: int
        :rtype: int
        """
        state=profit=0  #初始化总收益profit,当前价格下进行交易的损益state
        last_price=prices[0]   #前一天的价格记为last_price
        for price in prices[1:]:    #从第二天的价格开始遍历
            state+=price-last_price #若按当前价格卖掉,相比于前一天的损益
            if state>fee:   #若纯收益为正,则卖掉,更新收益并state归零
                profit+=state-fee
                state=0
            elif state<0:   #若亏本,state归零
                state=0
            last_price=price#记录当前价格作为下一次循环的前一天价格
        return profit
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值