一【题目类别】
- 贪心算法
二【题目难度】
- 中等
三【题目编号】
- 714.买卖股票的最佳时机含手续费
四【题目描述】
- 给定一个整数数组 prices,其中 prices[i]表示第 i 天的股票价格 ;整数 fee 代表了交易股票的手续费用。
- 你可以无限次地完成交易,但是你每笔交易都需要付手续费。如果你已经购买了一个股票,在卖出它之前你就不能再继续购买股票了。
- 返回获得利润的最大值。
- 注意:这里的一笔交易指买入持有并卖出股票的整个过程,每笔交易你只需要为支付一次手续费。
五【题目示例】
-
示例 1:
- 输入: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
-
示例 2:
- 输入:prices = [1,3,7,5,10,3], fee = 3
- 输出:6
六【解题思路】
- 基于贪心的策略:找到最低价格的买入点(含手续费)和合适的卖出点(大于成本),继续向后搜索还有没有更高的利润。
- 我们在买入的时候就把手续费算进去,所以它们一共加起来当作成本(base)
- 具体分为以下几种情况
- base<prices[i]:这个时候就已经产生利润了,但是后面可能还有更大的利润,所以加上当前的利润,更新base为当前值,如果有更大的利润,也加进来
- base>prices[i]+fee:这个时候说明找到了更低的成本(买入点),更新base为prices[i]+fee
- 其他情况产生的利润不足以让我们买卖,略过即可
- 最后返回结果即可
七【题目提示】
- 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
八【时间频度】
- 时间复杂度: O ( n ) O(n) O(n),其中 n n n为数组的长度
- 空间复杂度: O ( 1 ) O(1) O(1)
九【代码实现】
- Java语言版
package GreedyAlgorithm;
/**
* @Author: IronmanJay
* @Description: 714.买卖股票的最佳时机含手续费
* @CreateTime: 2022-11-11 08:53
*/
public class p714_BestTimeToBuyAndSellStockWithTransactionFee {
public static void main(String[] args) {
int[] prices = {1, 3, 2, 8, 4, 9};
int fee = 2;
int res = maxProfit(prices, fee);
System.out.println("res = " + res);
}
public static int maxProfit(int[] prices, int fee) {
if (prices.length <= 1) {
return 0;
}
int base = prices[0] + fee;
int profit = 0;
for (int i = 1; i < prices.length; i++) {
if (prices[i] > base) {
profit += prices[i] - base;
base = prices[i];
} else if (base > prices[i] + fee) {
base = prices[i] + fee;
}
}
return profit;
}
}
- C语言版
#include<stdio.h>
int maxProfit(int* prices, int pricesSize, int fee)
{
if (pricesSize <= 1)
{
return 0;
}
int base = prices[0] + fee;
int profit = 0;
for (int i = 1; i < pricesSize; i++)
{
if (prices[i] > base)
{
profit += prices[i] - base;
base = prices[i];
}
else if (prices[i] + fee < base)
{
base = prices[i] + fee;
}
}
return profit;
}
/*主函数省略*/
十【提交结果】
-
Java语言版
-
C语言版