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. 解題思路: 給定一個股票的價格序列prices,但是僅能交易一次,求最大利潤。也就是找出max(prices[j]-prices[i]),其中j > i。要求只需要遍歷一次序列就好了,那么就有兩種思路。第一種,每次找到當前最小的價格low,將當前的利潤與最大利潤做比較,直至得到最大利潤;第二種利用動態規劃的思想,用d[i]來i表示如果在第i天買出得到的最大利潤d[i] = max(d[i - 1] + prices[i] - prices[i - 1],0)。 現在給出第二種思路的代碼: code: int maxProfit(vector<int>& prices) { vector<int> d(prices.size(), 0); int maxp = 0; for (int i = 1; i < prices.size(); i++) { d[i] = d[i - 1] + prices[i] - prices[i - 1]; d[i] = max(0,d[i]); if (maxp < d[i]) maxp = d[i]; } return maxp; }