- descrption
Your are given an array of integersprices
, 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.
- 解题思路
利用动态规划算法。每天的交易有三种情况:买、卖、或不买也不卖。用money[i]假设第i天卖掉股票能获得的最多的钱,用hold[i]假设第i天保留股票持有股票的最大利润。在第i天,如果我们卖掉手中的股票,那么获得的最多的钱是前一天手里持有股票的利润加上卖出价格减去交易费,或者是前一天卖出的利润,如果前一天卖出能获得的钱更多,那么肯定就前一天卖出股票;如果我们没有卖掉股票,那么第i天持有股票的利润就是前一天卖出股票得到的最多的钱减去今天买股票的价格,或者是前一天保留股票的利润比今天大,那么就继续保留。
money[i] = max(sold[i - 1], hold[i - 1] + prices[i] - fee);
hold[i] = max(hold[i - 1], sold[i - 1] - prices[i]);
- 代码如下
class Solution {
public:
int maxProfit(vector<int>& prices, int fee) {
int money = 0;
int hold = -prices[0];
for(int d : prices){
int temp = money;
money = max(money, hold + d - fee);
hold = max(hold, temp - d);
}
return money;
}
};
如有错误请指出,谢谢!