121. Best Time to Buy and Sell Stock -Easy
2017-02-14 20:17
357 查看
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: 5
max. 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,所以最终返回3class 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
相关文章推荐
- 【Leetcode-Easy-121】Best Time to Buy and Sell Stock
- 121. Best Time to Buy and Sell Stock [easy] (Python)
- @121. Best Time to Buy and Sell Stock----Array----Easy---20160926
- 121. Best Time to Buy and Sell Stock 类别:动态规划 难度:easy
- Easy 121题 Best Time to Buy and Sell Stock
- LeetCode 121 Best Time to Buy and Sell Stock
- [LeetCode]121 Best Time to Buy and Sell Stock
- 121:Best Time to Buy and Sell Stock【数组】【两指针】
- 【LeetCode从零单排】No121 Best Time to Buy and Sell Stock
- LeetCode121:Best Time to Buy and Sell Stock
- leetcode || 121、Best Time to Buy and Sell Stock
- 121. Best Time to Buy and Sell Stock
- 121 Best time to buy and sell stock i
- Best Time to Buy and Sell Stock - LeetCode 121
- LeetCode(121)Best Time to Buy and Sell Stock
- [leetcode 121] Best Time to Buy and Sell Stock
- Lettcode_121_Best Time to Buy and Sell Stock
- LeetCode: Best Time to Buy and Sell Stock [121]
- leetcode_121题——Best Time to Buy and Sell Stock(动态规划)
- 121. Best Time to Buy and Sell Stock