Question
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天的股票价格。如果你仅被允许最多一次交易(买一次以及卖一次股票)。现在要求你设计出一个算法找到使利益最大的交易
Example
Input: [7, 1, 5, 3, 6, 4]
Output: 5max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)
Solution
动态规划解。我们需要维护一个最大利益的值max_profit和最低买入点low_buy,我们每遇到一个更低的买入点,我们都需要更新low_buy,而对于任意一个买入点,接下来每一天卖出得到有可能得到的利益我们都需要更新max_profit。比如[7, 2, 3, 1, 4],当遇到2,low_buy=2,遇到了3,我们得到当前max_profit=1,遇到了1,low_buy=2,遇到了4,max_profit=3,所以最终返回3
class Solution(object): def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ if len(prices) == 0: return 0 max_profit = 0 low_buy = prices[0] for index_p, p in enumerate(prices): # 如果当前股票价格小于之前的最低价格,则更新最低价格 if p < low_buy: low_buy = p # 更新最大收益 elif p - low_buy > max_profit: max_profit = p - low_buy return max_profit