[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.

给定一个数组,第i个元素代表股票第i天的价钱,只允许作一次买卖操作,求最大的利润。

从头到尾遍历一遍数组,不断的记录到当前为止的最低股价,并尝试计算以之前的最低股价买入,以当前的价格卖出,不断更新最大利润。时间复杂度o(n)。

代码如下:

 1 class Solution {
 2 public:
 3     int maxProfit(vector<int> &prices) {
 4         if (prices.size() == 0) return 0;
 5         int buy=prices[0];
 6         int profit = 0;
 7         for (int i = 0; i<prices.size(); i++)
 8         {
 9             if(prices[i] >= buy)
10             {
11                 profit = max (prices[i] - buy ,profit);
12             }
13             else
14             {
15                 buy = prices[i];
16             }
17         }
18         return profit;
19     }
20 };
原文地址:https://www.cnblogs.com/jostree/p/3703298.html