• 【力扣】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.

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    //动态规划
    public int maxProfit(int[] prices, int fee) {
    
            int length = prices.length;
            if(length < 2){
                return 0;
            }
    
            int buyer[] = new int[length];
            int sell[] = new int[length];
    
            buyer[0] = -prices[0];
            sell[0]=0;
    
            //当前为买入 或者 不变
            //buyer = Math.max(buyer[i-1],sell[i-1] - price[i]);
    
            //当天为卖出 或者不卖
            //sell = Math.max(sell[i-1] + price[i] - fee, buyer[i-1]);
    
            for(int i = 1 ; i < length ; i++){
                buyer[i] = Math.max(buyer[i-1],sell[i-1] - prices[i]);
                sell[i] = Math.max(buyer[i-1] + prices[i] - fee, sell[i-1]);
            }
            return sell[length-1];
    
            //时间复杂度O(n)
            //空间复杂度O(n)
        }
    //贪心算法,将手续费放到买入时计算
        public int maxProfit(int[] prices, int fee) {
    
            int length = prices.length;
            if(length < 2){
                return 0;
            }
            int min = prices[0] + fee;
            int result = 0;
            for(int i = 1 ; i < length ; i++){
    
                //如果当前价格 + fee比最小值还小,就把当前值作为最小值
                if(prices[i] + fee < min){
                    min = prices[i] + fee;
                } else if(prices[i] > min) {
                    //如果当前值大于最小值,则计算差值,并把当前值作为最小值
                    result += prices[i] - min;
                    min = prices[i] + fee;
                }
            }
            return result;
    
            //时间复杂度O(n)
            //空间复杂度O(1)
        }
    一个入行不久的Java开发,越学习越感觉知识太多,自身了解太少,只能不断追寻
  • 相关阅读:
    转: CEF嵌入到单文档mfc
    浅谈C++多态性
    C++面试整理1
    面试汇总
    【转】一些经典的笔试题
    C# 委托
    搭建Nuget
    thinkphp框架之模型(数据库查询)
    利用csc.exe 手动编译C#程序
    css
  • 原文地址:https://www.cnblogs.com/fengtingxin/p/14295197.html
Copyright © 2020-2023  润新知