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.
Example 1:
Input: [7, 1, 5, 3, 6, 4]
Output: 5
max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)
Example 2:
Input: [7, 6, 4, 3, 1]
Output: 0
In this case, no transaction is done, i.e. max profit = 0.
DP 思路的思考: 假设dp[i]为第 i 天的最大利润,则在第 i 天有两种选择,即在当天卖掉之前所有天中最低价买入的股票和在这之前已经卖掉股票(dp[i-1]),由此我们可以得到状态转移方程:dp[i] = max{ dp[i-1], prices[i]-minPrices },其中minPrices为第 i 天之前的买点,即我们沿途跟踪的最低价格。之前的方法可以视为对dp的优化。