• leetcode 123 Best Time to Buy and Sell Stock III


    是之前两道题leetcode Best Time to Buy and Sell Stockleetcode Best Time to Buy and Sell Stock II的加强版。

    这里要求只能买两次股票。

    做了一个多小时,试了好多次,终于AC了。

    思路:找到有可能为断点的地方,也就是出现递减的地方,递减了就说明有损失所以有可能卖出。

    对每个可能的分割点,计算左右两边的最大收益,求最大收益和leetcode Best Time to Buy and Sell Stock这个差不多。然后把所有可能的解记录,返回最大的解就是了。

    class Solution {
    public:
        int maxProfit(vector<int> &prices) 
        {
            int i = 0, tmpi = 0, len = prices.size(), minp = 0;
            vector<int> maxp;
            while(i < len - 1)
            {
                if (prices[i] >= prices[i + 1]) {i++; continue;}
                int curp = prices[i];
                int maxID = i + 1;
                while(i + 1 < len && prices[i] <= prices[i + 1]) { maxID = i + 1; i++;}
                //对于每个递减的部分左右分割
                tmpi = 0;
                minp = prices[tmpi];
                int tmpMax1 = 0;
                while(tmpi < maxID + 1)
                {
                    if (prices[tmpi] < minp)
                        minp = prices[tmpi];
                    else if (prices[tmpi] - minp > tmpMax1) tmpMax1 = prices[tmpi] - minp;
                    tmpi++;
                }
                //右边
                tmpi = maxID + 1;
                if (tmpi < len) minp = prices[tmpi];
                int tmpMax2 = 0;
                while(tmpi < len)
                {
                    if (prices[tmpi] < minp)
                        minp = prices[tmpi];
                    else if (prices[tmpi] - minp > tmpMax2) tmpMax2 = prices[tmpi] - minp;
                    tmpi++;
                }
                maxp.push_back(tmpMax1 + tmpMax2);
                i = maxID + 1;
            }
            
            int max1 = 0;
            for (int j = 0; j < maxp.size(); ++j)
                if (maxp[j] > max1)
                    max1 = maxp[j];
            return max1;
        }
    };

     胜之不武啊,原来我的方法是n方的方法,比普通的遍历所有的节点两边分割的方法好那么一点点,那终究是n方的。

    果然,学习了下,还有O(n)的方法。

    动态规划:

    这位大神

    进行优化:

    对于点j+1,求price[0..j+1]的最大profit时,很多工作是重复的,在求price[0..j]的最大profit中已经做过了。

    类似于Best Time to Buy and Sell Stock,可以在O(1)的时间从price[0..j]推出price[0..j+1]的最大profit。

    但是如何从price[j..n-1]推出price[j+1..n-1]?反过来思考,我们可以用O(1)的时间由price[j+1..n-1]推出price[j..n-1]。

    最终算法:

    数组l[i]记录了price[0..i]的最大profit,

    数组r[i]记录了price[i..n]的最大profit。

    已知l[i],求l[i+1]是简单的,同样已知r[i],求r[i-1]也很容易。

    最后,我们再用O(n)的时间找出最大的l[i]+r[i],即为题目所求。

    package Level4;
    
    import java.util.Arrays;
    
    /**
     * Best Time to Buy and Sell Stock III
     * 
     *  Say you have an array for which the ith element is the price of a given stock on day i.
    
    Design an algorithm to find the maximum profit. You may complete at most two transactions.
    
    Note:
    You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
    
    http://blog.csdn.net/pickless/article/details/12034365
     *
     */
    public class S123 {
    
        public static void main(String[] args) {
    //        int[] prices = {3,3,5,0,0,3,1,4};
            int[] prices = {2,1,2,0,1};
            System.out.println(maxProfit(prices));
        }
        
        // 基本思想是分成两个时间段,然后对于某一天,计算之前的最大值和之后的最大值
        public static int maxProfit(int[] prices) {
            if(prices.length == 0){
                return 0;
            }
            
            int max = 0;
            // dp数组保存左边和右边的利润最大值
            int[] left = new int[prices.length];        // 计算[0,i]区间的最大值
            int[] right = new int[prices.length];    // 计算[i,len-1]区间的最大值
            
            process(prices, left, right);
            
            // O(n)找到最大值
            for(int i=0; i<prices.length; i++){
                max = Math.max(max, left[i]+right[i]);
            }
            
            return max;
        }
        
        public static void process(int[] prices, int[] left, int[] right){
            left[0] = 0;
            int min = prices[0];        // 最低买入价
            
            // 左边递推公式
            for(int i=1; i<left.length; i++){
                left[i] = Math.max(left[i-1], prices[i]-min);    // i的最大利润为(i-1的利润)和(当前卖出价和之前买入价之差)的较大那个
                min = Math.min(min, prices[i]);        // 更新最小买入价
            }
            
            right[right.length-1] = 0;
            int max = prices[right.length-1];        // 最高卖出价
            // 右边递推公式
            for(int i=right.length-2; i>=0; i--){
                right[i] = Math.max(right[i+1], max-prices[i]);    // i的最大利润为(i+1的利润)和(最高卖出价和当前买入价之差)的较大那个
                max = Math.max(max, prices[i]);        // 更新最高卖出价
            }
            
    //        System.out.println(Arrays.toString(left));
    //        System.out.println(Arrays.toString(right));
        }
    
    }

    下面的解法主要是能把两次的限制推广到k次交易:

    这道题是Best Time to Buy and Sell Stock的扩展,现在我们最多可以进行两次交易。我们仍然使用动态规划来完成,事实上可以解决非常通用的情况,也就是最多进行k次交易的情况。
    这里我们先解释最多可以进行k次交易的算法,然后最多进行两次我们只需要把k取成2即可。我们还是使用“局部最优和全局最优解法”。我们维护两种量,一个是当前到达第i天可以最多进行j次交易,最好的利润是多少(global[i][j]),另一个是当前到达第i天,最多可进行j次交易,并且最后一次交易在当天卖出的最好的利润是多少(local[i][j])。下面我们来看递推式,全局的比较简单,

    global[i][j]=max(local[i][j],global[i-1][j]),

    也就是去当前局部最好的,和过往全局最好的中大的那个(因为最后一次交易如果包含当前天一定在局部最好的里面,否则一定在过往全局最优的里面)。

    全局(到达第i天进行j次交易的最大收益) = max{局部(在第i天交易后,恰好满足j次交易),全局(到达第i-1天时已经满足j次交易)

    对于局部变量的维护,递推式是

    local[i][j]=max(global[i-1][j-1]+max(diff,0),local[i-1][j]+diff),

    也就是看两个量,第一个是全局到i-1天进行j-1次交易,然后加上今天的交易,如果今天是赚钱的话(也就是前面只要j-1次交易,最后一次交易取当前天),第二个量则是取local第i-1天j次交易,然后加上今天的差值(这里因为local[i-1][j]比如包含第i-1天卖出的交易,所以现在变成第i天卖出,并不会增加交易次数,而且这里无论diff是不是大于0都一定要加上,因为否则就不满足local[i][j]必须在最后一天卖出的条件了)。

    局部(在第i天交易后,总共交易了j次) =  max{情况2,情况1}

    情况1:在第i-1天时,恰好已经交易了j次(local[i-1][j]),那么如果i-1天到i天再交易一次:即在第i-1天买入,第i天卖出(diff),则这不并不会增加交易次数!【例如我在第一天买入,第二天卖出;然后第二天又买入,第三天再卖出的行为  和   第一天买入,第三天卖出  的效果是一样的,其实只进行了一次交易!因为有连续性

    情况2:第i-1天后,共交易了j-1次(global[i-1][j-1]),因此为了满足“第i天过后共进行了j次交易,且第i天必须进行交易”的条件:我们可以选择1:在第i-1天买入,然后再第i天卖出(diff),或者选择在第i天买入,然后同样在第i天卖出(收益为0)。

    上面的算法中对于天数需要一次扫描,而每次要对交易次数进行递推式求解,所以时间复杂度是O(n*k),如果是最多进行两次交易,那么复杂度还是O(n)。空间上只需要维护当天数据皆可以,所以是O(k),当k=2,则是O(1)。

    http://blog.csdn.net/linhuanmars/article/details/23236995

    public class Solution {
        public int maxProfit(int[] prices) {
            return max(prices, 2);
        }
        
        public int max(int[] prices, int k) {       // k: k times transactions
            int len = prices.length;
            if(len == 0) {
                return 0;
            }
            int[][] local = new int[len][k+1];      // local[i][j]: max profit till i day, j transactions, where there is transaction happening on i day
            int[][] global = new int[len][k+1];     // global[i][j]: max profit across i days, j transactions
            for(int i=1; i<len; i++) {
                int diff = prices[i] - prices[i-1];
                for(int j=1; j<=k; j++) {
                    local[i][j] = Math.max(global[i-1][j-1]+Math.max(diff,0), local[i-1][j]+diff);
                    global[i][j] = Math.max(global[i-1][j], local[i][j]);
                }
            }
            return global[len-1][k];
        }
    }

    20150403: 动态规划

    class Solution {
    public:
        int maxProfit(vector<int> &prices) {
            int n = prices.size();
            if (n <= 1) return 0;
            int left[n], right[n]; // left[i] records 0 to ith day's profits, right[i] i to (n-1)th days'
            left[0] = 0;
            int minVal = prices[0];
            for (int i = 1; i < n; i++){
                left[i] = max(left[i-1], prices[i]- minVal);
                minVal = min(minVal, prices[i]);
            }
            right[n-1] = 0;
            int maxVal = prices[n-1];
            for (int i = n-2; i > 0; i--){
                right[i] = max(right[i+1], maxVal - prices[i]);
                maxVal = max(maxVal, prices[i]);
            }
            int profits = 0;
            for (int i = 1; i < n; i++){
                if (profits < left[i] + right[i])
                    profits = left[i] + right[i];
            }
            return profits;
        }
    };
     
  • 相关阅读:
    Prometheus环境搭建系列(三):监控redis服务器(redis_exporter)
    Java诊断神器:Arthas常用功能
    sql优化练习
    navicat:[Err] 1055
    Prometheus环境搭建系列(二):监控mysql服务器(mysqld_exporter)
    【笔试必备】常见sql笔试题
    将博客搬至CSDN
    springboot假死、连接泄露
    测试字符串
    阿里云初次使用教程
  • 原文地址:https://www.cnblogs.com/higerzhang/p/4138950.html
Copyright © 2020-2023  润新知