代码改变世界

Best Time to Buy and Sell Stock

2015-04-07 21:46  笨笨的老兔子  阅读(200)  评论(0编辑  收藏  举报

给定一个向量,该向量表示一只股票在第i天的价格,y要使得股票收益最大就应该在第i天买入,第i+n天卖出,求最大收益的值是多少

思路:用一个变量记录最小值,一个变量记录最大收益,从头到尾扫描一次价格,当扫描到第i天的价格时,如果这个价格比最小值小,则替换,如果比最小值大,则计算此刻的收益是否大于最大收益,大于则替换,否则继续。

  1. class Solution {
  2. public:
  3. int maxProfit(vector<int> &prices) {
  4. int profit = 0;
  5. int minIndex = 0;
  6. for (size_t i = 1; i < prices.size(); i++)
  7. {
  8. if (prices[i] < prices[minIndex])
  9. {
  10. minIndex = i;
  11. }
  12. else if (prices[i] - prices[minIndex] > profit)
  13. {
  14. profit = prices[i] - prices[minIndex];
  15. }
  16. }
  17. return profit;
  18. }
  19. };