码迷,mamicode.com
首页 > 其他好文 > 详细

121. Best Time to Buy and Sell Stock

时间:2016-01-11 17:50:28      阅读:129      评论:0      收藏:0      [点我收藏+]

标签:

Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

  本题只需进行一次遍历,维护两个指针,一个指向i之前的最低价low,一个指向最低价之后且i之前的最高价high,如果prices[i]高于high,则更新high为prices[i],

如果prices[i]<low,则算出high-low,看看是否要更新最大利润,然后high和low共同指向i。

代码:

 1 int maxProfit(vector<int>& prices)
 2 {
 3     if (prices.size()==0||prices.size()==1)
 4         return 0;
 5     int low=prices[0],high=prices[0],profit=0;
 6     for (int i=1;i<prices.size();i++)
 7     {
 8         if (prices[i]>high)
 9             high=prices[i];
10         else if (prices[i]<low)
11         {
12             if (profit<high-low)
13                 profit=high-low;
14             low=prices[i];
15             high=prices[i];
16         }
17     }
18     int pre=high-low;
19     return pre>profit?pre:profit;
20 }

 

121. Best Time to Buy and Sell Stock

标签:

原文地址:http://www.cnblogs.com/zhang-hill/p/5121696.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!