leetcode-Best Time to Buy and Sell Stock

一定要判断好边界条件,edge case很关键。

 1 #include <vector>
 2 #include <iostream>
 3 using namespace std;
 4 
 5 class Solution {
 6 public:
 7     int maxProfit(vector<int> &prices) {
 8         //a[i]表示在prices[i]卖出的最大收益(prices[i]-截止a[i]为止的min)。
 9         if (prices.size() ==0)
10             return 0;
11         int min = prices[0];
12         int maxP = 0;
13         
14         for (int i = 1; i < prices.size(); i++)
15         {
16             if (prices[i] - min>maxP)
17                 maxP = prices[i] - min;
18             if (prices[i] < min)
19                 min = prices[i];
20         }
21         return maxP;
22     }
23 };
24 int main()
25 {
26     int a[] = { 5, 2, 4, 9, 7 };
27     vector<int> prices(a,a+4);
28     Solution s;
29     cout << s.maxProfit(prices) << endl;
30     return 0;
31 }
原文地址:https://www.cnblogs.com/forcheryl/p/3997037.html