(leetcode)Best Time to Buy and Sell Stock

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.

维护一个全局最大的maxprofit,每次更新后都是全局最大的。

 1 class Solution {
 2 public:
 3     int maxProfit(vector<int>& prices) {
 4         if(prices.size() == 0) return 0;
 5         int sellprice = prices[0];
 6         int maxprofit = 0;
 7         for(int i = 1;i < prices.size();++i)
 8         {
 9             sellprice = min(sellprice,prices[i]);
10             maxprofit = max(prices[i]-sellprice,maxprofit);
11         }
12         return maxprofit;
13     }
14 };

 

posted @ 2015-08-22 22:53  sunalive  Views(111)  Comments(0)    收藏  举报