###### tags: `Leetcode` `medium` `dynamic programming` `array` `greedy` `python` `c++` # 714. Best Time to Buy and Sell Stock with Transaction Fee ## [題目連結:] https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/ ## 題目: You are given an array ```prices``` where ```prices[i]``` is the price of a given stock on the ```ith``` day, and an integer fee representing a transaction fee. Find the maximum profit you can achieve. You may complete as many transactions as you like, but you need to pay the transaction fee for each transaction. **Note:** You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again). **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. ``` **Example 2:** ``` Input: prices = [1,3,7,5,10,3], fee = 3 Output: 6 ``` ## 解題想法: * 此題為股票題,給一系列股票交易價格,每次交易都會有手續費(fee),求最大獲益 * 使用DP: * 定義兩組 * unHold=[0]* len(prices) **手中沒持有股票的獲利** * Hold=[0]* len(prices) **手中持有股票的獲利** * 初始Hold[0]=-prices[0] * 轉移方程: * unHold[i]: 表示今天手裡沒有股票了 * max(昨天手中就沒有股票, 昨天有股票+今天賣-手續費) * Hold[i]: 表示今天手裡有股票 * max(昨天持有的, 昨天手中沒股票-今天買) ## Python: ``` python= class Solution(object): def maxProfit(self, prices, fee): """ :type prices: List[int] :type fee: int :rtype: int """ unHold=[0]*len(prices) #手中沒持有股票的獲利 Hold=[0]*len(prices) #手中持有股票的獲利 Hold[0]=-prices[0] for i in range(1,len(prices)): #昨天的vs昨天有買+今天賣-手續費 unHold[i]=max(unHold[i-1],Hold[i-1]+prices[i]-fee) #昨天持有的vs昨天積蓄-今天買 Hold[i]=max(Hold[i-1],unHold[i-1]-prices[i]) print(unHold,Hold) return unHold[-1] result=Solution() ans=result.maxProfit(prices = [1,3,2,8,4,9], fee = 2) print(ans) ``` ## C++: ``` cpp= #include<bits/stdc++.h> using namespace std; class Solution { public: int maxProfit(vector<int>& prices, int fee) { int n=prices.size(); vector<int> Hold(n, 0), unHold(n, 0); Hold[0]=-prices[0]; for (int i=1; i<n; i++){ unHold[i]=max(unHold[i-1], Hold[i-1]+prices[i]-fee); Hold[i]=max(Hold[i-1], unHold[i-1]-prices[i]); } return unHold[n-1]; } }; ```