Best Time to Buy and Sell Stock

  1. Best Time to Buy and Sell Stock
    有一個price數組,標記第i天交易股票的花費。如果只允許一次交易必須先買後賣,最大收益。

    找price數組中的最小的,然後其後續與其的最大差值爲最大收益。

  2. Best Time to Buy and Sell Stock II
    交易任意次數,求整個過程中的最大收益。

    price[i]>price[i-1], 則其差值加入收益中。

  3. Best Time to Buy and Sell Stock with Cooldown
    交易任意多次,但是如果你這次賣了,下次你不能買,只有下下次之後才能買,即中間停一次。
    http://www.cnblogs.com/grandyang/p/4997417.html

 public int maxProfit(int[] prices) {
        int buy = Integer.MIN_VALUE; //爲了使第一次不能爲buy,則將初始buy變爲整數最小值即負數
        int sell = 0, buy1, sell2 = 0;
        for (int i = 0; i < prices.length; i++){
            buy1 = buy;
            buy = Math.max(buy1, sell2 - prices[i]); //此處sell2爲sell[i-2]
            sell2 = sell; //此處sell爲i-1次的,則在下一次循環中,尚未計算sell前,其相對第i+1爲其前2次的,即爲sell2
            sell = Math.max(sell, buy1 + prices[i]);
        }
        return sell;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章