【LeetCode每日一题】——714.买卖股票的最佳时机含手续费

一【题目类别】

  • 贪心算法

二【题目难度】

  • 中等

三【题目编号】

  • 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<=5104
  • 1 < = p r i c e s [ i ] < 5 ∗ 1 0 4 1 <= prices[i] < 5 * 10^4 1<=prices[i]<5104
  • 0 < = f e e < 5 ∗ 1 0 4 0 <= fee < 5 * 10^4 0<=fee<5104

八【时间频度】

  • 时间复杂度: O ( n ) O(n) O(n),其中 n n n为数组的长度
  • 空间复杂度: O ( 1 ) O(1) O(1)

九【代码实现】

  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;
    }

}
  1. 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;
}

/*主函数省略*/

十【提交结果】

  1. Java语言版
    在这里插入图片描述

  2. C语言版
    在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

IronmanJay

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值