121. Best Time to Buy and Sell Stock

 1 static int wing=[]()
 2 {
 3     std::ios::sync_with_stdio(false);
 4     cin.tie(NULL);
 5     return 0;
 6 }();
 7 
 8 class Solution 
 9 {
10 public:
11     int maxProfit(vector<int>& prices) 
12     {
13         int buy=INT_MAX;
14         int sell=0;
15         int sz=prices.size();
16         for(int i=0;i<sz;i++)
17         {
18             buy=min(buy,prices[i]);
19             sell=max(sell,prices[i]-buy);
20         }
21         return sell;
22     }
23 };

扫描一遍数组,用当前值减去之前的最小值,即为当前可获得的最大利润。扫描完毕后,即为买卖一次能获得的最大利润。

猜你喜欢

转载自www.cnblogs.com/zhuangbijingdeboke/p/9057447.html