首頁  >  問答  >  主體

java - 为什么leetcode的这个题是一个动态规划?

leetcode地址: https://leetcode.com/problems...

我对这个算法慢慢的还是可以想通的, 但是为什么他是动态规划呢? 动态规划不是要话分子问题, 列出递推方程的吗?但是这个题并不能列出递推方程的...还是说我思考的方式不对. 望指点一下这个算法的思想

public class BestTimeToBuyAndSellStockIII
{
    public int maxProfit(int[] prices)
    {
        if(prices.length == 0) return 0;
        int ans = 0;
        int n = prices.length;

        //正向遍历,opt[i]表示 prices[0...i]内做一次交易的最大收益.
        int opt[] = new int[n];
        opt[0] = 0;
        int low = prices[0];
        int curAns = 0;
        for(int i = 1; i < n; i++)
        {
            if(prices[i] < low)
                low = prices[i];
            else if(curAns < prices[i] - low)
                curAns = prices[i] - low;
            opt[i] = curAns;
        }

        //逆向遍历, opt[i]表示 prices[i...n-1]内做一次交易的最大收益.
        int optReverse[] = new int[n];
        optReverse[n - 1] = 0;
        curAns = 0;
        int high = prices[n - 1];
        for(int i = n - 2; i >= 0; i--)
        {
            if(prices[i] > high) high = prices[i];
            else if(curAns < high - prices[i]) curAns = high - prices[i];
            optReverse[i] = curAns;
        }

        //再进行划分,分别计算两个部分
        for(int i = 0; i < n; i++)
        {
            int tmp = opt[i] + optReverse[i];
            if(ans < tmp) ans = tmp;
        }
        return ans;
    }
}
PHPzPHPz2716 天前401

全部回覆(1)我來回復

  • 天蓬老师

    天蓬老师2017-04-18 09:47:25

    這個問題首先被分解成了兩個問題:正向遍歷,反向遍歷。
    這一步應該不算是動態規劃。

    但是兩個小問題內部使用的就是動態規劃演算法了。
    每一小步都是一個遞歸的定義:已知前K天的最佳交易方式,那麼當加入K+1天的價格,最佳交易方式是什麼。
    K從0已知漲到N,於是就得到了前N天的最佳交易方式。

    回覆
    0
  • 取消回覆