[LeetCode-121] Best Time to Buy and Sell Stock

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.

 

很水,没什么好说的。

 

 1 class Solution {
 2      public:
 3          int maxProfit(vector<int> &prices) {
 4              // Start typing your C/C++ solution below
 5              // DO NOT write int main() function
 6              if (0 == prices.size()) {
 7                  return 0;
 8              }
 9              int max_profit = 0, last_min = INT_MAX;
10              for (int i = 0; i < prices.size(); ++i) {
11                  if (prices.at(i) < last_min) {
12                      last_min = prices.at(i);
13                  } else {
14                      max_profit = max<int>(max_profit, prices.at(i) - last_min);
15                  }
16              }
17              return max_profit;
18          }  
19  };
View Code

 

posted on 2013-08-29 08:39  似溦若岚  阅读(151)  评论(0编辑  收藏  举报

导航