• 买股票题目一种很好的通用解法


    https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/?tab=Description

    题目是最多两次,但是下面的解法非常好,也能够覆盖仅仅一次的情况。

    https://discuss.leetcode.com/topic/5934/is-it-best-solution-with-o-n-o-1/2

    代码很简短,思路也非常好:

    public class Solution {
        public int maxProfit(int[] prices) {
            int hold1 = Integer.MIN_VALUE, hold2 = Integer.MIN_VALUE;
            int release1 = 0, release2 = 0;
            for(int i:prices){                              // Assume we only have 0 money at first
                release2 = Math.max(release2, hold2+i);     // The maximum if we've just sold 2nd stock so far.
                hold2    = Math.max(hold2,    release1-i);  // The maximum if we've just buy  2nd stock so far.
                release1 = Math.max(release1, hold1+i);     // The maximum if we've just sold 1nd stock so far.
                hold1    = Math.max(hold1,    -i);          // The maximum if we've just buy  1st stock so far. 
            }
            return release2; ///Since release1 is initiated as 0, so release2 will always higher than release1.
        }
    }

    但是上面对于最多N次这种更加通用的形式,就不太好用了。

    https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/?tab=Description

    上面对于最多买n次类型的题目,要用到DP才行。

    解法看这里:

    https://discuss.leetcode.com/topic/8984/a-concise-dp-solution-in-java

    其实含义也很明确:

    tmpMax是当前时间状态持股之后的最大收益(很可能是负的)

    t[i][j]是记录的实际收益。

    public int maxProfit(int k, int[] prices) {
            int len = prices.length;
            if (k >= len / 2) return quickSolve(prices);
            
            int[][] t = new int[k + 1][len];
            for (int i = 1; i <= k; i++) {
                int tmpMax =  -prices[0];
                for (int j = 1; j < len; j++) {
                    t[i][j] = Math.max(t[i][j - 1], prices[j] + tmpMax);
                    tmpMax =  Math.max(tmpMax, t[i - 1][j - 1] - prices[j]);
                }
            }
            return t[k][len - 1];
        }
        
    
        private int quickSolve(int[] prices) {
            int len = prices.length, profit = 0;
            for (int i = 1; i < len; i++)
                // as long as there is a price gap, we gain a profit.
                if (prices[i] > prices[i - 1]) profit += prices[i] - prices[i - 1];
            return profit;
        }
  • 相关阅读:
    iOS 解析xml
    带滚动条html,js获取鼠标位置
    iOS ViewController利用代理页面传值
    Android Volley完全解析
    32位linux中无法使用AVD的解决方案
    8年前在公交上被年轻小伙打了,76岁大爷苦练功夫“复仇”成功...网友:大爷,你一定是天蝎座的吧
    退学,离家出走,卖房创业,在他即将烧完最后一笔钱时,获250万元融资
    夏普将在迪拜推出植物工厂种草莓
    国产手机出货量今年要追平苹果三星,到底有多难?
    原生ajax动态添加数据
  • 原文地址:https://www.cnblogs.com/charlesblc/p/6439256.html
Copyright © 2020-2023  润新知