121. Best Time to Buy and Sell Stock

121. 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.

解題思路:

給定一個股票的價格序列prices,但是僅能交易一次,求最大利潤。也就是找出max(prices[j]-prices[i]),其中j > i。要求只需要遍歷一次序列就好了,那么就有兩種思路。第一種,每次找到當前最小的價格low,將當前的利潤與最大利潤做比較,直至得到最大利潤;第二種利用動態規劃的思想,用d[i]來i表示如果在第i天買出得到的最大利潤d[i] = max(d[i - 1] + prices[i] - prices[i - 1],0)。
現在給出第二種思路的代碼:

code:

int maxProfit(vector<int>& prices)
 {
        vector<int> d(prices.size(), 0);
        int maxp = 0;
        for (int i = 1; i < prices.size(); i++) {
            d[i] = d[i - 1] + prices[i] - prices[i - 1];
            d[i] = max(0,d[i]);
            if (maxp < d[i])
              maxp = d[i];
        }
        return maxp;
 }
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容