[LeetCode] 121 - 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.

 

class Solution {
public:
  int maxProfit(vector<int>& prices) {
    int size = prices.size();
    if (size <= 1) {
      return 0;
    }
    int min_ = prices[0];
    int res_ = prices[1] - prices[0];
    for (int i = 2; i < size; ++i) {
      min_ = min(prices[i-1], min_);
      res_ = max(prices[i] - min_, res_);
    }
    return res_ < 0 ? 0 : res_;
  }
};

 

posted on 2015-09-10 18:17  tuituji  阅读(129)  评论(0编辑  收藏  举报

导航