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

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

Medium

问题描述:

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:

1
2
3
4
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.

题目分析:

给定数组prices,第i-th元素表示在第i天的股票价格,每一手股票,需要收取的手续费为fee,同时最多持有一只股票,我们需要寻找最好的买入卖出策略,从而得到最大利润。

这一题同样可以使用动态规划思想来解决,我们需要两个状态,一个是买状态,一个是卖状态。买状态其实保存的是当前最小的购买花费,卖状态保存的是直到目前最大的收益。买入卖出操作均有前一天的买卖状态决定,当收益
“为大”,就执行卖出操作。

以题目所给示例为例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
buy[0] = -fee - prices[0] = -3 #第一天买入股票的花费

buy[1] = max(buy[0], sell[0] - prices[1] - fee) = -3 #第二天执行买入操作
sell[1] = max(sell[0], buy[0] + prices[1]) = 0

buy[2] = max(buy[1], sell[1] - prices[2] - fee) = -3 #第三天决定继续持有
sell[2] = max(sell[1], buy[1] + prices[2]) = 0

buy[3] = max(buy[2], sell[2] - prices[3] - fee) = -3 #第四天执行卖出操作
sell[3] = max(sell[2], buy[2] + prices[3]) = 5

buy[4] = max(buy[3], sell[3] - prices[4] - fee) = -1 #第五天继续购买股票
sell[4] = max(sell[3], buy[3] + prices[4]) = 5

buy[5] = max(buy[4], sell[4] - prices[5] - fee) = -1 #第六天卖出
sell[5] = max(sell[4], buy[4] + prices[5]) = 8

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution(object):
def maxProfit(self, prices, fee):
"""
:type prices: List[int]
:type fee: int
:rtype: int
"""

if len(prices) <= 1:
return 0

buy, sell = [0] * len(prices), [0] * len(prices)
buy[0] = -prices[0] - fee

for i in range(1, len(prices)):
buy[i] = max(buy[i - 1], sell[i - 1] - prices[i] - fee)
sell[i] = max(sell[i - 1], buy[i - 1] + prices[i])

return sell[-1]