首页 > 其他 > 详细

Leetcode 121. Best Time to Buy and Sell Stock

时间:2017-05-15 09:17:08      阅读:299      评论:0      收藏:0      [点我收藏+]

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

原文:http://www.cnblogs.com/lettuan/p/6854753.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!