Best Time to Sell and Buy Stock

这道题想了很多,但是想多了。这个题思路很简单,如果当前值大于最小值,就计算差,和最大利润值比较。

 1 class Solution {
 2 public:
 3     int maxProfit(vector<int> &prices) {
 4         if(prices.size()==0)
 5             return 0;
 6         int length = prices.size();
 7         int minVal = prices[0];
 8         int maxP = 0;
 9 
10         for(int i=1;i<length;i++)
11            {
12                if(prices[i]<minVal)
13                  minVal = prices[i];
14                if(prices[i]-minVal>maxP)
15                  maxP = prices[i]-minVal;
16            }
17         return maxP;
18     }
19 };

 

posted @ 2015-02-04 20:57  醉剑客  阅读(133)  评论(0编辑  收藏  举报