1. 程式人生 > >best-time-to-buy-and-sell-stock系列(貪心與動態規劃)

best-time-to-buy-and-sell-stock系列(貪心與動態規劃)

Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

解題思路:這個問題有很多種解法,最簡單的做法是貪心。

    解法1: 首先設第 i 個元素之前最小的股票價格為minprice,初始化為 price[0],最大利潤maxprofit 初始化為0; 然後遍歷整個price陣列,maxprofit = price[i] - minprice ,然後更新minprice = min( minprice, price[i] ) ;

    解法2: 為了引出後面的解法,這裡介紹一種畫蛇添足的方法: 初始化兩個一維陣列 local[N],global[N](全0),分別表示前i天最多進行一次交易的區域性最優和全域性最優。這裡的區域性最優指的是,在第i天賣出股票所得到的最大收入,全域性最優指的是在第i天或第i天之前賣出股票所得的最大收入。

    設天數編號為1..N,從 i == 2 開始遍歷陣列,local[i] = max(  local[i-1] + price[i]-price[i-1] , price[i] - price[i-1] ) ; global[i] = max(local[i], global [i -1] ); 最終結果存放在global[N] ;

//解法2:
class Solution {
public:
    int maxProfit(vector<int> &prices) {
        int size = prices.size();
        int *local = new int[ size ];
        int *global = new int[ size ];
        for( int i = 0 ;  i< size ; i++){
            local[i]=global[i] = 0;
        }
        for( int i = 1 ;  i< size ; i++){
            local[i] = max(local[i-1] + prices[i] - prices[i-1],
                           prices[i] - prices[i-1]);
            global[i] = max( global[i-1], local[i]);
        }
        return global[size-1];
    }
};
二、best-time-to-buy-and-sell-stock-ii