首页 > 其他 > 详细

121. Best Time to Buy and Sell Stock

时间:2016-01-11 17:50:17      阅读:128      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!