zoukankan      html  css  js  c++  java
  • 动态规划(股票交易)---需要交易费用的股票交易

    需要交易费用的股票交易

    714. Best Time to Buy and Sell Stock with Transaction Fee (Medium)

    Input: prices = [1, 3, 2, 8, 4, 9], fee = 2
    Output: 8
    Explanation: The maximum profit can be achieved by:
    Buying at prices[0] = 1
    Selling at prices[3] = 8
    Buying at prices[4] = 4
    Selling at prices[5] = 9
    The total profit is ((8 - 1) - 2) + ((9 - 4) - 2) = 8.
    

    题目描述:

      没有冷冻期,每交易一次都要支付一定的费用。

    思路分析:

    动态规划的思想:

      sell[i],表示该天结束后手里没有股票的情况下,已经获得的最大收益。

      hold[i],表示该天结束后手里有股票的情况下,已经获得的最大收益。

    状态转移方程是这样的:

      sell[i],表示手里没有股票的收益,这种可能性是今天卖了,或者啥也没干。今天啥也没干那就是sell[i]=sell[i-1],今天卖了,那么sell[i]就是前一天有股票的收益加上今天卖出去股票的价格再减去交易费。sell[i]=hold[i-1]+price[i]-fee

     因此:sell[i]=max(sell[i-1],hold[i-1]+price[i]-fee)

      hold[i],表示今天手里有股票的收益,这种可能性是今天买了股票或者啥也没干。今天啥也没干那就是hold[i]=hold[i-1],今天买了股票,那么hold[i]=sell[i-1]-price[i]

      因此:hold[i]=max(hold[i-1],sell[i-1]-price[i])

    代码:

    public int maxProfit(int []prices,int fee){
        if(prices==null||prices.length==0)
            return 0;
        int []sell=new int[prices.length];
        int []hold=new int[prices.length];
        sell[0]=0;
        hold[0]=-prices[0];
        for(int i=1;i<prices.length;i++){
            sell[i]=Math.max(sell[i-1],hold[i-1]+prices[i]-fee);
            hold[i]=Math.max(hold[i-1],sell[i-1]-prices[i]);
        }
        return sell[prices.length-1];
    }
    
  • 相关阅读:
    【ccf线上赛普及组 2020】
    【小总结】2020.3.6
    DP优化
    noip2012day2
    noip2012day1
    3.28真题
    数据结构总结
    noi online 普及组
    小总结
    20200229模拟赛
  • 原文地址:https://www.cnblogs.com/yjxyy/p/11121364.html
Copyright © 2011-2022 走看看