1. 程式人生 > 實用技巧 >[LeetCode] 714. Best Time to Buy and Sell Stock with Transaction Fee

[LeetCode] 714. Best Time to Buy and Sell Stock with Transaction Fee

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 integerfeerepresenting 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.

買賣股票的最佳時機含手續費。這是股票系列的最後一題了。這道題允許你交易多次,但是每次交易的時候是有一個手續費,用fee表示。依然是請你返回獲得利潤的最大值。

思路依然是動態規劃。還是建立一個二維的DP陣列,dp[i][j]表示第 i 天持有和不持有股票的最大收益。j 只有可能是0或1,表示不持有股票和持有股票。這道題多的一個變數fee可以放在買入的時候,可以把他理解為成本的一部分。其他部分跟版本二的動態規劃解法沒有區別。分享一個寫的很好的題解

時間O(n)

空間O(mn)

Java實現

 1 class Solution {
 2     public int maxProfit(int[] prices, int fee) {
 3         int len = prices.length;
 4         // corner case
 5         if (len < 2) {
 6             return 0;
 7         }
 8 
 9         // dp[i][j] 表示 [0, i] 區間內,到第 i 天(從 0 開始)狀態為 j 時的最大收益'
10         // j = 0 表示不持股,j = 1 表示持股
11         // 並且規定在買入股票的時候,扣除手續費
12         int[][] dp = new int[len][2];
13         dp[0][0] = 0;
14         dp[0][1] = -prices[0] - fee;
15         for (int i = 1; i < len; i++) {
16             dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1] + prices[i]);
17             dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][0] - prices[i] - fee);
18         }
19         return dp[len - 1][0];
20     }
21 }

LeetCode 題目總結