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];
    }
    
  • 相关阅读:
    一定要在3 20前完成所有的程序开发工作
    浅谈图像处理方向的就业前景[转)
    期待牛人指教的问题?
    vc6 7工程转vc8时的问题
    今天的工作计划
    定点数与浮点数区别
    difference between texRECT and tex2D
    Render to Texture
    不明白gluperpective的fovy参数
    批处理程序教程(转)
  • 原文地址:https://www.cnblogs.com/yjxyy/p/11121364.html
Copyright © 2011-2022 走看看