Best Time to Buy and Sell Stock @leetcode

Plan A:

 1 int maxProfit(vector<int> &prices) {
 2         // IMPORTANT: Please reset any member data you declared, as
 3         // the same Solution instance will be reused for each test case.
 4         int i;
 5         int res=0;
 6         if(prices.size() == 0 || prices.size()==1)
 7         {
 8             return 0;
 9         }
10         vector<int> highestAfterThis;
11         highestAfterThis.resize(prices.size()-1);
12         for(i=highestAfterThis.size()-1;i>=0;--i)
13         {
14             if(i == highestAfterThis.size() -1)
15                 highestAfterThis[i] = prices[prices.size()-1];
16             else
17             {
18                 highestAfterThis[i] = prices[i+1]>highestAfterThis[i+1]?prices[i+1]:highestAfterThis[i+1];
19             }
20         }
21         for(i=0;i<prices.size()-1;++i)
22         {
23             int tmp = highestAfterThis[i] - prices[i];
24             if(tmp > res )res = tmp;
25         }
26         return res;
27     }

Plan B:

 1 int maxProfit(vector<int> &prices) {
 2         // IMPORTANT: Please reset any member data you declared, as
 3         // the same Solution instance will be reused for each test case.
 4         int i;
 5         int res=0;
 6         if(prices.size() == 0 || prices.size()==1)
 7         {
 8             return 0;
 9         }
10         int min=prices[0];
11         for(i=0;i<prices.size();++i)
12         {
13             if(prices[i] < min) min = prices[i];
14             if(prices[i] - min > res) res = prices[i] - min;
15         }
16         return res;
17     }
原文地址:https://www.cnblogs.com/rogarlee/p/3420550.html