LeetCode 714. 买卖股票的最佳时机含手续费
题目描述
思路分析
解法一:动态规划(推荐)
核心思路:
cash表示当前不持股的最大利润,hold表示当前持股的最大利润。- 每天更新:
cash = max(cash, hold + price - fee)hold = max(hold, cash - price)(注意使用更新前的 cash)。
复杂度分析:
- 时间复杂度:O(n),其中 n 表示价格数组长度。
- 空间复杂度:O(1),仅使用常数额外空间。
class Solution {
public int maxProfit(int[] prices, int fee) {
int cash = 0;
int hold = -prices[0];
for (int i = 1; i < prices.length; i++) {
int prevCash = cash;
cash = Math.max(cash, hold + prices[i] - fee);
hold = Math.max(hold, prevCash - prices[i]);
}
return cash;
}
}
func maxProfit(prices []int, fee int) int {
cash := 0
hold := -prices[0]
for i := 1; i < len(prices); i++ {
prevCash := cash
if hold+prices[i]-fee > cash {
cash = hold + prices[i] - fee
}
if prevCash-prices[i] > hold {
hold = prevCash - prices[i]
}
}
return cash
}
相似题目
| 题目 | 难度 | 考察点 |
|---|---|---|
| 121. 买卖股票的最佳时机 | 简单 | 贪心 |
| 122. 买卖股票的最佳时机 II | 简单 | 贪心 |
| 714. 买卖股票的最佳时机含手续费 | 中等 | DP |
| 309. 买卖股票的最佳时机含冷冻期 | 中等 | DP |
| 188. 买卖股票的最佳时机 IV | 困难 | DP |
本博客所有文章除特别声明外,均采用
CC BY-NC-SA 4.0
许可协议,转载请注明出处!