【leetcode】714. Best Time to Buy and Sell Stock with Transaction Fee
题目如下:
Your are given an array of integers
prices
, for which thei
-th element is the price of a given stock on dayi
; and a non-negative integerfee
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] = 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.
Note:
0 < prices.length <= 50000
.0 < prices[i] < 50000
.0 <= fee < 50000
.
解题思路:对于任意一天i来说,可以有跳过(cooldown包含在内)/买入/卖出三种操作,记dp[i][0],dp[i][1],dp[i][2]为第i天是做这三种操作时候可以获得的最大收益。很显然 dp[i][0] = max(dp[i-1][0],dp[i-1][1],dp[i-1][2]);dp[i][1]的情况分为第一次买入/非第一次买入,所以有 dp[i][1] = max(dp[i][1] ,-price[i],dp[j][2] - prices[i] ) (j<i) ,-prices[i]表示第一次买入,在当前节点获得的收益是负数,因为钱已经变成了股票,dp[j][2] - prices[i]表示本次买入是在第j天卖出后的后序操作,中间不存在其他的交易,这里还需要减去fee,因为每次卖出的时候需要收取手续费;同理dp[i][2] = max(dp[i][2],dp[j][1] + prices[i]-fee),这是因为卖出是要在买入之后。当然,对于每个i来说,并不需要去比较0~j天的所有数据,只要记录之前出现过的dp[j][1]和dp[j][2]的最大值即可。最后的结果是 max(0, dp[-1][0], dp[-1][2]),因为最后一天要么跳过,要么卖出,不会再有买入的操作。
代码如下:
class Solution(object): def maxProfit(self, prices, fee): """ :type prices: List[int] :type fee: int :rtype: int """ if len(prices) <= 1: return 0 dp = [] for i in prices: dp.append([-float('inf'), -float('inf'), -float('inf')]) # 0:do nothing, 1:buy ,2:sell dp[0][1] = -prices[0] #dp[1][1] = -prices[1] #dp[1][2] = prices[1] - prices[0] - fee max_buy = max(dp[0][1], dp[1][1]) max_sell = -float('inf') for i in range(1, len(dp)): dp[i][0] = max(dp[i - 1][0], dp[i - 1][1], dp[i - 1][2]) dp[i][2] = max(dp[i][2], max_buy + prices[i]-fee) dp[i][1] = max(dp[i][1], -prices[i], max_sell - prices[i]) max_sell = max(max_sell, dp[i][2]) max_buy = max(max_buy, dp[i][1]) #print dp return max(0, dp[-1][0], dp[-1][2])