一、题目描述
- 给定一个整数数组
prices
和 整数fee
,其中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 |
提示:
- 1 < = n u m . l e n g t h < = 35 1 <= num.length <= 35 1<=num.length<=35
- n u m num num 仅由数字(0 - 9)组成
- 1 < = p r i c e s . l e n g t h < = 5 ∗ 1 0 4 1 <= prices.length <= 5 * 10^4 1<=prices.length<=5∗104
- 1 < = p r i c e s [ i ] < 5 ∗ 1 0 4 1 <= prices[i] < 5 * 10^4 1<=prices[i]<5∗104
- 0 < = f e e < 5 ∗ 1 0 4 0 <= fee < 5 * 10^4 0<=fee<5∗104
二、求解思路:二维动态规划(含内存优化Python3代码)
- 沿用 122 - 买卖股票的最佳时机 II 的二维动态规划思路, 在进行内存优化。
- 做改进的地方就在于每次进行购买股票时,多减去
fee
即可。 - 内存优化:每一天只有两种操作(买入或者卖出),理想情况是在最低点买入高点卖出,这时只要比较每天的这两种操作哪个获得的收益最大即可,此时只需要常数的内存,大大减少了内存且提高了运行效率。(文中采用贪心算法的思想给出了内存优化的Python3代码)
C++代码
class Solution {
public:
int maxProfit(vector<int>& prices, int fee) {
int n = prices.size();
int dp[n][2];
dp[0][0] = 0; dp[0][1] = -prices[0] - fee;
for(int i = 1; i < n; i++) {
dp[i][0] = max(dp[i-1][0], dp[i-1][1] + prices[i]);
dp[i][1] = max(dp[i-1][0] - prices[i] - fee, dp[i-1][1]);
}
return dp[n-1][0];
}
};
Python3代码
class Solution:
def maxProfit(self, prices: List[int], fee: int) -> int:
n = len(prices)
dp = [ [[0],[0]] for i in range(n)]
dp[0][0] = 0
dp[0][1] = -prices[0] - fee
for i in range(1,n):
dp[i][0] = max(dp[i-1][0], dp[i-1][1] + prices[i])
dp[i][1] = max(dp[i-1][0] - prices[i] - fee, dp[i-1][1])
return dp[n-1][0]
内存优化:Python3代码
class Solution:
def maxProfit(self, prices: List[int], fee: int) -> int:
# 假设第一天买入
operate = prices[0] + fee
Profit = 0
for price in prices:
# 买高了,反悔,从更低位买入
if price + fee < operate:
operate = price + fee
# 卖了,更新买入价
elif price > operate:
Profit += price - operate
operate = price
return Profit
Java代码
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] - fee;
for(int i = 1; i < n; i++) {
dp[i][0] = Math.max(dp[i-1][0], dp[i-1][1] + prices[i]);
dp[i][1] = Math.max(dp[i-1][0] - prices[i] - fee, dp[i-1][1]);
}
return dp[n-1][0];
}
}
复杂度分析
- 时间复杂度: O ( n ) O(n) O(n)。
- 空间复杂度: O ( n ) O(n) O(n),内存优化后为 O ( 1 ) O(1) O(1)。
三、参考文章
[1] https://blog.csdn.net/qq_40430360/article/details/124738846