標籤:des style blog io ar color os 使用 sp
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.
首先,問題轉換為數學語言:對數組A[n], 對任意i < j < n, 求出max(A[j] - A[i]).
可以使用O(n^2)的方法得到結果。
以下分析動態規劃方法:
對於輸入prices[n], 如果已知profit[i - 1],
1) 當prices[i] <= prices[i - 1]時,顯然,profit[i] = profit[i - 1]
2)當prices[i] > prices[i - 1]時, 記bottom = min(prices[0, 1, ..., i]), 如果
prices[i] - bottom > profit[i - 1] 則有
profit[i] = prices[i] - bottom
否則,profit[i] = profit[i - 1]
1 int maxProfit(vector<int> &prices) 2 { 3 int n = prices.size(), bottom, max_profit; 4 if (n <= 1) 5 return 0; 6 int *profit = new int[n]; 7 profit[0] = 0; 8 bottom = prices[0]; 9 for (int i = 1; i < n; i++)10 {11 bottom = min(bottom, prices[i]);12 if (prices[i] > prices[i - 1] && prices[i] - bottom > profit[i - 1])13 {14 profit[i] = prices[i] - bottom;15 }16 else17 {18 profit[i] = profit[i - 1];19 }20 }21 max_profit = profit[n - 1];22 delete profit;23 return max_profit;24 }
leetcode. Best Time to Buy and Sell Stock