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.
題目描述:給出一組股票價格的數組,買賣的次數不限,每次買入必須在賣出之後,而且要收取一定的手續費,求最大的收益方法
思路:這是一道動態規劃的問題,這種問題,一般當前的收益與前一天有關,所以只有兩種狀態就是買和賣,其中hold就是收益 nothold就是買入就是持有股票數最大
買:hold = Math.max(hold, notHold - prices[i]);
賣:notHold = Math.max(notHold, hold + prices[i] - fee);
這裏就需要hold 和 nothold的初始值,最終輸出hold, 因爲最後一天手裏是沒有股票的
在討論區還看到了一種非常好的方法,就是使用了棧來求出最大的收益
思路是在棧中保存了[ buy , sell], 當sell 爲0 的時候表示沒有賣出
遍歷數組,記錄當前的價格爲price
- 當棧頂交易sell 爲 0 ,並且 price <= buy 將棧頂buy 替換爲price
- 當price >= max(sell,buy+free) 則替換棧頂sell 爲 price
- 否則 將[price , 0] 壓棧
當棧元素>1 並且合併棧頂的兩組交易可以獲得最大收益的時候,將棧頂的兩個交易合併
public int maxProfit(int[] prices, int fee) {
if (prices == null || prices.length <= 1) {
return 0;
}
int len = prices.length;
int hold = -prices[0];
int notHold = 0;
for (int i = 1; i < prices.length; i++) {
hold = Math.max(hold, notHold - prices[i]);
notHold = Math.max(notHold, hold + prices[i] - fee);
}
return notHold;
}