Best Time to Buy and Sell Stock IV

leetcode中的股票問題(4)

第四題還是有點難的,特別是在連續完成前3題後,思路可能就頓時侷限了,主要參考別人的實現,我這裏做一些分析。
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/

原題

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 k transactions.
翻譯:和前一題基本一樣,只是從最多2手交易改成了最多k 手交易。

問題分析

這裏我的直覺就是用動態規劃來解決這個問題,但是具體怎麼做呢?
很容易想到的就是維護變量profit(i,j) ,這裏ij 表示在i天最多做j手交易。
profit(i,j)=Max(profit(i1,j),profitAt(i,j))
其中profitAt(i,j) 表示,在第i天一定要發生交易的情況下最多做j手交易的最大收益(有點拗口,吼吼吼),因爲這樣才能對profit(i,j) 做一個合理的劃分。
profitAt(i,j) 呢?怎麼遞推呢?
我們說profitAt(i,j)=Max(profit(i1,j1)+Max(0,diff),profitAt(i1,j)+diff) ,其中diff=price(i)price(i1)
怎麼理解呢,同樣是要做一個劃分,既然第i天必定有交易(必定有賣出行爲),那我對這一手的買進時間做這樣劃分:買進時間>=i1 或者<i1 ,對於>=i1 的情況,在i1 天之前就完成j1 手交易,而最後一次買賣的收益是Max(0,diff) ;對於<i1 的情況,我們完全可以用profitAt(i1,j)+diff) 來遞推,直接加上diff 的原因是將原本在第i1 天賣掉的股票移到第i天賣掉,直接加上這兩天的差價就行!
然後就很簡單了,直接上代碼。
下面的代碼中 global就是profit()函數,而local就是profitAt()函數。

代碼

public int maxProfit(int k, int[] prices) {
    if(prices==null || prices.length==0)
            return 0;
    //如果k>一半天數,問題退化成問題(3)了
    if(k > prices.length/2)
    {
        int sum =0;
        for(int i = 0 ; i < prices.length-1 ; i++)
        {
            int gain = prices[i+1] - prices[i];
            if(gain > 0)
                sum += gain;
        }
        return sum;
    }

    int[][] global=new int[prices.length][k+1];
    int[][] local=new int[prices.length][k+1];
    for(int i=0;i<prices.length-1;i++)
    {
        int diff=prices[i+1]-prices[i];
        for(int j=0;j<=k-1;j++)
        {
            local[i+1][j+1]=Math.max(global[i][j]+Math.max(diff,0),local[i][j+1]+diff);
            global[i+1][j+1]=Math.max(global[i][j+1],local[i+1][j+1]);
        }
    }
    return global[prices.length-1][k];
}

接下來我們會去看看在leetcode中和數組以及鏈表的“rotate”操作相關的幾個問題~

發佈了36 篇原創文章 · 獲贊 3 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章