買賣股票的最佳時機I、II、III、IV

買賣股票的最佳時機I

假設有一個數組,它的第i個元素是一支給定的股票在第i天的價格。如果你最多隻允許完成一次交易(例如,一次買賣股票),設計一個算法來找出最大利潤。
思路:這個比較簡單,只要遍歷一次就好,同時更新最小的值。可以得到最大的利潤。
代碼如下:

class Solution {
public:
    /*
     * @param prices: Given an integer array
     * @return: Maximum profit
     */
    int maxProfit(vector<int> &prices) {
        // write your code here
        if(prices.size()<2)return 0;//防止越界
        int maxprofit = 0;//最大利潤
        int minlow = prices[0];//最低價格
        for(int i = 1;i != prices.size();++i){
            minlow = min(minlow,prices[i]);
            maxprofit = max(maxprofit,prices[i] - minlow);
        }
        return maxprofit;
    }
};

買賣股票的最佳時機II

假設有一個數組,它的第i個元素是一個給定的股票在第i天的價格。設計一個算法來找到最大的利潤。你可以完成儘可能多的交易(多次買賣股票)。然而,你不能同時參與多個交易(你必須在再次購買前出售股票)。
思路:這個問題,顯然只要能有收益的時候就脫出賣,這樣就可以獲得最大的利潤。
代碼如下:

class Solution {
public:
    /*
     * @param prices: Given an integer array
     * @return: Maximum profit
     */
    int maxProfit(vector<int> &prices) {
        // write your code here
        //這裏應該是有利潤就要出手
        if(prices.size()<2)return 0;
        int low = prices[0];
        int profit = 0;
        for(int i=1;i!=prices.size();++i){
            if(prices[i]>low){
                profit = profit+prices[i]-low;
            }
            low = prices[i];
        }
        return profit;
    }
};

買賣股票的最佳時機III&IV

假設你有一個數組,它的第i個元素是一支給定的股票在第i天的價格。設計一個算法來找到最大的利潤。你最多可以完成 k 筆交易。注意事項:你不可以同時參與多筆交易(你必須在再次購買前出售掉之前的股票)
樣例
給定價格 = [4,4,6,1,1,4,2,5], 且 k = 2, 返回 6.
思路:典型的動態規劃問題。
代碼如下:

public class Solution {
    /*
     * @param K: An integer
     * @param prices: An integer array
     * @return: Maximum profit
     */
    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;
   }
}

另一種簡單的解法

在Discuss中看到一種很棒的解法,代碼只有10行左右,但是不是很好理解。

第二種解法的核心是假設手上最開始只有0元錢,那麼如果買入股票的價格爲price,手上的錢需要減去這個price,如果賣出股票的價格爲price,手上的錢需要加上這個price。

它定義了4個狀態:

Buy1[i]表示前i天做第一筆交易買入股票後剩下的最多的錢;

Sell1[i]表示前i天做第一筆交易賣出股票後剩下的最多的錢;

Buy2[i]表示前i天做第二筆交易買入股票後剩下的最多的錢;

Sell2[i]表示前i天做第二筆交易賣出股票後剩下的最多的錢;

那麼

Sell2[i]=max{Sell2[i-1],Buy2[i-1]+prices[i]}
Buy2[i]=max{Buy2[i-1],Sell[i-1]-prices[i]}
Sell1[i]=max{Sell[i-1],Buy1[i-1]+prices[i]}
Buy1[i]=max{Buy[i-1],-prices[i]}

可以發現上面四個狀態都是隻與前一個狀態有關,所以可以不使用數組而是使用變量來存儲即可。

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int buy1=numeric_limits<int>::min();
        int buy2=numeric_limits<int>::min();
        int sell1=0;
        int sell2=0;
        for(int i=0;i<prices.size();i++)
        {
            sell2=max(sell2,buy2+prices[i]);
            buy2=max(buy2,sell1-prices[i]);
            sell1=max(sell1,buy1+prices[i]);
            buy1=max(buy1,-prices[i]);
        }
        return sell2;
    }

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