題目
給定一個整數數組 prices,其中第 i 個元素代表了第 i 天的股票價格 ;整數 fee 代表了交易股票的手續費用。
你可以無限次地完成交易,但是你每筆交易都需要付手續費。如果你已經購買了一個股票,在賣出它之前你就不能再繼續購買股票了。
傳回獲得利潤的最大值。
注意:這裡的一筆交易指買入持有并賣出股票的整個過程,每筆交易你隻需要為支付一次手續費。
示例 :
輸入:prices = [1, 3, 2, 8, 4, 9], fee = 2
輸出:8
解釋:能夠達到的最大利潤:
在此處買入 prices[0] = 1
在此處賣出 prices[3] = 8
在此處買入 prices[4] = 4
在此處賣出 prices[5] = 9
總利潤: ((8 - 1) - 2) + ((9 - 4) - 2) = 8
示例 2:
輸入:prices = [1,3,7,5,10,3], fee = 3
輸出:6
提示:
1 <= prices.length <= 5 * 104
1 <= prices[i] < 5 * 104
0 <= fee < 5 * 104
算法
動态規劃
- dp[i][0] 表示第 i 天交易完後手裡沒有股票的最大利潤
- dp[i][1] 表示第 i 天交易完後手裡持有一支股票的最大利潤(i 從 0 開始)。
class Solution {
public int maxProfit(int[] prices, int fee) {
int n = prices.length;
int[][] dp = new int[n][2];
dp[0][0] = 0;
dp[0][1] = -prices[0];
for (int i = 1; i < n; ++i) {
dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1] + prices[i] - fee);
dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][0] - prices[i]);
}
return dp[n - 1][0];
}
}
- dp[i][0] 表示為今天沒有持有股票。
- dp[i - 1][0] 表示昨天也沒有
- dp[i - 1][1] + prices[i] - fee);表示昨天有,但是今天賣出去了
dp[i][1]表示為今天持有股票。
- dp[i - 1][1] 表示昨天也持有股票
- dp[i - 1][1] + prices[i] - fee);表示昨天沒有,但是今天買進來了
貪心
先來看看沒有手續費的那道題目
給定一個數組,它的第 i 個元素是一支給定股票第 i 天的價格。
設計一個算法來計算你所能擷取的最大利潤。你可以盡可能地完成更多的交易(多次買賣一支股票)。
注意:你不能同時參與多筆交易(你必須在再次購買前出售掉之前的股票)。
示例 1:
輸入: [7,1,5,3,6,4]
輸出: 7
解釋: 在第 2 天(股票價格 = 1)的時候買入,在第 3 天(股票價格 = 5)的時候賣出, 這筆交易所能獲得利潤 = 5-1 = 4 。
随後,在第 4 天(股票價格 = 3)的時候買入,在第 5 天(股票價格 = 6)的時候賣出, 這筆交易所能獲得利潤 = 6-3 = 3 。
示例 2:
輸入: [1,2,3,4,5]
輸出: 4
解釋: 在第 1 天(股票價格 = 1)的時候買入,在第 5 天 (股票價格 = 5)的時候賣出, 這筆交易所能獲得利潤 = 5-1 = 4 。
注意你不能在第 1 天和第 2 天接連購買股票,之後再将它們賣出。
因為這樣屬于同時參與了多筆交易,你必須在再次購買前出售掉之前的股票。
示例 3:
輸入: [7,6,4,3,1]
輸出: 0
解釋: 在這種情況下, 沒有交易完成, 是以最大利潤為 0。
// 貪心思路
public int maxProfit(int[] prices, int fee) {
if (prices == null || prices.length == 0) {
return 0;
}
int profit = 0;
int in_hand = prices[0];
for (int i = 1; i < prices.length; i++) {
if(prices[i] < in_hand){
in_hand = prices[i];
}else if(prices[i] > in_hand){
profit += prices[i] - in_hand;
in_hand = prices[i];
}
}
return profit;
}
加上手續費之後
![](https://img.laitimes.com/img/__Qf2AjLwojIjJCLyojI0JCLiYTMfhHLlN3XnxCM38FdsYkRGZkRG9lcvx2bjxCMy8VZ6l2csQ1RZZDTtxUNW1yS2kmMaZTWHpVNQFnY1wUa2UTQClGVF5UMR9Fd4VGdsATNfd3bkFGazxycykFaKdkYzZUbapXNXlleSdVY2pESa9VZwlHdssmch1mclRXY39CXldWYtlWPzNXZj9mcw1ycz9WL49zZuBnL2EzM3gDM2kDO2UjZygTZhRWNjRTYwQGOhZGZ1gjZ2E2Lc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.png)
這裡參考大佬圖檔https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/solution/ti-hao-122mei-you-shou-xu-fei-jia-yi-dian-dong-xi-/
public int maxProfit(int[] prices, int fee) {
if (prices == null || prices.length == 0) {
return 0;
}
int profit = 0;
int in_hand = prices[0];
for (int i = 1; i < prices.length; i++) {
if(prices[i] < in_hand){
in_hand = prices[i];
}else if(prices[i] - fee > in_hand){
profit += prices[i] - fee - in_hand;
in_hand = prices[i] - fee;
}
}
return profit;
}