leetcode刷题:贪心算法17(买卖股票的最佳时机含手续费)

714. 买卖股票的最佳时机含手续费

力扣题目链接

给定一个整数数组 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.

注意:

  • 0 < prices.length <= 50000.
  • 0 < prices[i] < 50000.
  • 0 <= fee < 50000.

首先要明确一点,我们一开始是有一只股在手,但不一定是prices[0],所以贪心思想,我们逐个选最低的股票作为当前手上持有的股。
如果当前股票的价格+手续费 > 初始股票价格。就sum加上这个收益。
同时 假设 我今天又原价买了一股,往后找找能不能收益,如果能收益,那就再加上,如果不能收益,没有了,那我就不假设。

package com.programmercarl.greed;

/**
 * @ClassName MaxProfit2
 * @Descriotion TODO
 * @Author nitaotao
 * @Date 2022/7/18 17:47
 * @Version 1.0
 * https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/
 * 714. 买卖股票的最佳时机含手续费
 **/
public class MaxProfit2 {
    public int maxProfit(int[] prices, int fee) {
        int sum = 0;
        //当前最小收益
        int minProfit = prices[0];
        for (int i = 1; i < prices.length; i++) {
            //如果当前价位比最低价小,就记录最低价
            if (prices[i] < minProfit) {
                minProfit = prices[i];
            } else if (prices[i] > minProfit + fee) {
                //有收益就加上
                sum += prices[i] - minProfit - fee;
                //假设今天继续买当天的
                minProfit = prices[i] - fee;
            }
        }
        return sum;
    }

    public static void main(String[] args) {
        System.out.println(new MaxProfit2().maxProfit(new int[]{1, 3, 2, 8, 4, 9}, 2));
        System.out.println(new MaxProfit2().maxProfit(new int[]{1, 3, 7, 5, 10, 3}, 3));
    }
}

在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值