题目
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] = 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.
解题思路
采用动态规划的方法,一开始比较容易想到的思路是设置一个收益数组 pro
,令 pro[i]
表示第 i
天的最大收益,然后考虑 pro[i]
与 pro[i - 1, i - 2 ... 0]
的关系。在第 i
天,我们只有三个操作:
- 不买也不卖。此时
pro[i] = pro[i - 1]
。 - 买。此时
pro[i] = pro[i - 1] - prices[i]
。 - 卖。此时
pro[i] = pro[i - 1] + prices[i] - fee
。
这样,似乎可以天真地认为一个动态转移方程就出来了:
然而这个方程根本不可行,因为 pro[i−1]>pro[i−1]−prices[i] 是肯定成立的,也就是说利用上面的动态转移方程将永远也执行不了买股票的操作!
上面的思路行不通,根本原因是“买股票”和“卖股票”这两个操作是无法单独地衡量其收益的,这一次的“卖”操作必须减去上一次的“买”操作才能衡量收益,同理,这一次的“买”操作也必须结合上一次的“卖”操作来衡量收益。因此,我们需要维护两种第 i
天的最大收益:一种是第 i
天执行“买”操作的最大收益 buy_pro[i]
,另一种是第 i
天执行“卖”操作的最大收益 sell_pro[i]
,这样,动态转移方程就变成了:
这里要特别注意
buy_pro[i]
表示的是第
i
天执行“买”操作的最大
收益,而不是
花费,因此有
sell_pro[i]=max{sell_pro[i−1], prices[i]+buy_pro[i−1]−fee}
而不是
sell_pro[i]=max{sell_pro[i−1], prices[i]−buy_pro[i−1]−fee}
。计算到最后时,只需比较
sell_pro
和
buy_pro
的最后一个元素哪个较大,选择最大的收益返回即可。
上述的动态转移方程需要
O(n)
的空间复杂度,但是观察可以发现,第 i
天的操作的收益只与第 i - 1
天的操作收益有关,因此根本不需要维护这样的两个数组,只要使用两个变量 buy_pro
和 sell_pro
即可。
C++代码实现
class Solution {
public:
int maxProfit(vector<int>& prices, int fee) {
// 初始化,第一天只能买,不能卖
int buy_profit = -prices[0], sell_profit = 0;
for (int i = 1; i < prices.size(); ++i) {
// 如果 buy_profit 被改变,
// 即 buy_profit = sell_profit - prices[i],
// 则 sell_profit 必然不会改变,反之亦然。
// buy_profit 和 sell_profit 之中只有一个能改变,
// 保证了两者之中必有一个是前一天的最大收益值,
// 这是不用维护两个数组,降低空间复杂度的关键!
buy_profit = max(buy_profit, sell_profit - prices[i]);
sell_profit = max(sell_profit, prices[i] + buy_profit - fee);
}
return max(buy_profit, sell_profit);
}
};