首页 > 代码库 > Leetcode 121. Best Time to Buy and Sell Stock

Leetcode 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.

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.

 

如果当前时刻 i 买入,那么对应于这个买入所能达到的最大收益就是当前价格和之后所有价格的max之间的差。所以我们要求一个maxPriceAfter list,来存储i之后的最高价格。显然只要倒叙求一遍max最大值就可以。

 

 1 class Solution(object):
 2     def maxProfit(self, prices):
 3         """
 4         :type prices: List[int]
 5         :rtype: int
 6         """
 7             
 8         n = len(prices)
 9         if n <= 1:
10             return 0
11         
12         maxPriceAfter = [0]*n
13         maxPriceAfter[-1] = prices[-1]
14         
15         peak = prices[-1]
16         for i in range(n-1, -1, -1):
17             peak = max(peak, prices[i])
18             maxPriceAfter[i] = peak
19         
20         maxProfit = 0
21         
22         for i in range(n):
23             maxProfit = max(maxProfit, maxPriceAfter[i]-prices[i])
24         
25         return maxProfit

或者维护一个从最开始到当前时刻的最低价格,当年价格减去这个最低价格就是当前卖出所能达到的最高利润。

 

class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
            
        n = len(prices)
        if n <= 1:
            return 0
        
        lowPrices = prices[0]
        
        maxProfit = 0
        
        for i in range(n):
            lowPrices = min(lowPrices, prices[i])
            maxProfit = max(maxProfit, prices[i]-lowPrices)
            
        return maxProfit

 

Leetcode 121. Best Time to Buy and Sell Stock