【12月19日】LeetCode刷题日志(三):Best Time to Buy and Sell Stock with Transaction Fee

题目描述:
Your are given an array of integers prices, for which the i-th element is the price of a given stock on day i; and a non-negative integer fee representing a transaction fee.
You may complete as many transactions as you like, but you need to pay the transaction fee for each transaction. You may not buy more than 1 share of a stock at a time (ie. you must sell the stock share before you buy again.)
这是一个很有意思的题目,其目标是求得利润的最大化。
给定一组数组int[] prices,分别表示每天的股票的价格;要求制定合理的买入-买出策略,尽可能多的获取收益。简化计算,题目还限制了最多只能持有一支股票。且每次卖出股票需要支付fee的手续费。
此外,还有以下关于具体数值的限制条件:

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

分析:
一般来说,有三种决策:买入、卖出、不做动作。
具体来说,对于第i天,如果手上有股票,在这一天可以选择“卖出”(并在支付fee)或者“不做动作”;如果手上没有股票,在这一天可以选择“买入”或者“不做动作”。需要衡量的就是,在第i-1天的状态已知的情况下,如何确定第i天最高收益。
设函数T_i_k表示最高收益,i表示第i天,k表示执行动作之后手上的股票数量(本题限制最大为1),那么
T_i_1=Math.max(T_i-1_1, T_i-1_0 - price[i]);
T_i_0=Math.max(T_i-1_0, T_i-1_1 + price[i] -fee);
对于以上公式的解释,假设第i天持有股票为1,那么有两种情况,要么是在i-1天就持有且第i天不做动作;要么是i-1天不持有,但是在第i天进行买入。收益分别对应T_i-1_1, T_i-1_0 - price[i]。只要max以上两只就可以知道在持有一支股票的情况下最大收益是多少;类似可推出T_i_0的情况。
令,最有一天一定是持有股票为0,即股票肯定全部出手。所有最后需要返回T_n_0(n为考察周期)。
具体代码如下:

 public int maxProfit(int[] prices, int fee) {
        // 持有股票为0
        int T_0 = 0;
        // 持有股票为1
        int T_1 = -50001;
        for(int price : prices){
            int T_0_old = T_0;
            T_0 = Math.max(T_0, T_1 + price - fee);
            // System.out.println(T_0);
            T_1 = Math.max(T_1, T_0_old - price);
            // System.out.println(T_1);
        }
        return T_0;
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值