714 Best Time to Buy and Sell Stock with Transaction Fee 買賣股票的最佳時(shí)機(jī)含手續(xù)費(fèi)
Description:
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:
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
Constraints:
1 <= prices.length <= 5 * 10^4
1 <= prices[i] < 5 * 10^4
0 <= fee < 5 * 10^4
題目描述:
給定一個(gè)整數(shù)數(shù)組 prices,其中第 i 個(gè)元素代表了第 i 天的股票價(jià)格 膀篮;非負(fù)整數(shù) fee 代表了交易股票的手續(xù)費(fèi)用早处。
你可以無限次地完成交易果元,但是你每筆交易都需要付手續(xù)費(fèi)。如果你已經(jīng)購買了一個(gè)股票鸽素,在賣出它之前你就不能再繼續(xù)購買股票了。
返回獲得利潤的最大值。
注意:
這里的一筆交易指買入持有并賣出股票的整個(gè)過程粒氧,每筆交易你只需要為支付一次手續(xù)費(fèi)。
示例 :
示例 1:
輸入: prices = [1, 3, 2, 8, 4, 9], fee = 2
輸出: 8
解釋: 能夠達(dá)到的最大利潤:
在此處買入 prices[0] = 1
在此處賣出 prices[3] = 8
在此處買入 prices[4] = 4
在此處賣出 prices[5] = 9
總利潤: ((8 - 1) - 2) + ((9 - 4) - 2) = 8.
說明:
0 < prices.length <= 50000.
0 < prices[i] < 50000.
0 <= fee < 50000.
思路:
動(dòng)態(tài)規(guī)劃
對(duì)于每一天只有兩種狀態(tài), 要么手上持有股票, 要么當(dāng)天賣出股票并支付手續(xù)費(fèi)
設(shè) dp[i][0] 表示當(dāng)天不持有股票時(shí)的收益, dp[i][1] 表示當(dāng)天持有股票時(shí)的收益
dp[i][0] = max(dp[i - 1][1] + prices[i] - fee, dp[i - 1][0]), 當(dāng)天沒有持有股票時(shí), 收益為前一天沒有持有股票和當(dāng)天賣出股票并減去手續(xù)費(fèi)的收益的較大值
dp[i][1] = max(dp[i - 1][0] - prices[i], dp[i - 1][1]), 當(dāng)天持有股票, 收益為前一天持有股票和當(dāng)天買入股票收益的較大值
最后返回 dp[n][0] 表示手上沒有股票的最大收益
初始化 dp[0][0] = 0, dp[0][1] = -prices[0]
注意到只需要前一天的收益的記錄, 可以將空間復(fù)雜度壓縮到 O(1)
時(shí)間復(fù)雜度為 O(n), 空間復(fù)雜度為 O(1)
代碼:
C++:
class Solution
{
public:
int maxProfit(vector<int>& prices, int fee)
{
int a = 0, b = -prices.front(), c = 0, d = 0, n = prices.size();
for (int i = 1; i < n; i++)
{
a = max(d - prices[i], b);
c = max(b + prices[i] - fee, d);
d = c;
b = a;
}
return c;
}
};
Java:
class Solution {
public int maxProfit(int[] prices, int fee) {
int a = 0, b = -prices[0], c = 0, d = 0, n = prices.length;
for (int i = 1; i < n; i++) {
a = Math.max(d - prices[i], b);
c = Math.max(b + prices[i] - fee, d);
d = c;
b = a;
}
return c;
}
}
Python:
class Solution:
def maxProfit(self, prices: List[int], fee: int) -> int:
a, b, c, d, n = 0, -prices[0], 0, 0, len(prices)
for i in range(1, n):
a, b, c, d = max(d - prices[i], b), max(d - prices[i], b), max(b + prices[i] - fee, d), max(b + prices[i] - fee, d)
return c