【best-time-to-buy-and-sell-stock】

Say you have an array for which the i thelement is the price of a given stock on dayi.

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.


題意:用一個數組表示股票每天的價格,數組第i個表示股票在第i天的價格,

class Solution {
public:
    int maxProfit(vector<int> &prices) 
    {
       if(prices.size()<=1)
       {
           return 0;
       }
        
       int maxProfit=0;
       int curMin=prices[0];
       for(int i=1; i<prices.size(); i++)
       {
           curMin=min(curMin, prices[i]);
           maxProfit=max(maxProfit, prices[i]-curMin);
       }
        
        return maxProfit;
    }
};


如果只允許進行一次交易,也就是說只允許買一隻股票並賣掉;
求最大收益;


思路:
動態規劃,從前向後遍歷數組,記錄當前出現過的最低價格,作爲買入的價格,
並計算以當天價格出售的收益,作爲可能的最大收益,整個遍歷過程中,
出現過的最大收益就是所求。



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章