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

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以前的最低價low,一個指向最低價以後且i以前的最高價high,若是prices[i]高於high,則更新high爲prices[i],code

若是prices[i]<low,則算出high-low,看看是否要更新最大利潤,而後high和low共同指向i。blog

代碼:element

 1 int maxProfit(vector<int>& prices)
 2 {
 3     if (prices.size()==0||prices.size()==1)
 4         return 0;
 5     int low=prices[0],high=prices[0],profit=0;
 6     for (int i=1;i<prices.size();i++)
 7     {
 8         if (prices[i]>high)
 9             high=prices[i];
10         else if (prices[i]<low)
11         {
12             if (profit<high-low)
13                 profit=high-low;
14             low=prices[i];
15             high=prices[i];
16         }
17     }
18     int pre=high-low;
19     return pre>profit?pre:profit;
20 }
相關文章
相關標籤/搜索