首页 > 其他 > 详细

leetcode-Best Time to Buy and Sell Stock

时间:2014-09-27 18:43:31      阅读:301      评论:0      收藏:0      [点我收藏+]

一定要判断好边界条件,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 }

 

leetcode-Best Time to Buy and Sell Stock

原文:http://www.cnblogs.com/forcheryl/p/3997037.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!