leetcode_[python/C++]_121/122/123/188.Best Time to Buy and Sell Stock I/II/III/IV

我们先拿出来前三道题,因为他们都是array中的题目。这是leetcode种经典的一系列题,涉及到动态规划和贪心算法。按照我的理解,贪心是满足当前条件的最优值我们就将它最为最优解,也就是大家说的局部最优值,而动态规划是要记录下来达到当前最优解的所有途径,由局部一步步得到全局最优。

这几道题都是给你一个股票每日价格表,让你得到不同条件下能挣的最多的钱。 
121题是只允许买卖一次,要保证卖的时间晚于买的日期,第一反应找最大值和最小值,最大的早于最小的,那么就找次大和次小,这样肯定很麻烦,从这个过程已经能感受到一点动态规划的感觉。是的没错,这道题就是用动态规划,我们维持两个变量,最低买入价格和当前可达到的最高利润。将第一天的价格初始化为最低价格,从第二天开始遍历,小于最低价格那么我们更新最低价格变量。将第i天的价格减去最低价格,即为第i天卖出得到的利润。比较该利润与最大利润之间的关系,取最大值赋给最大利润。 以这一天的价格作为卖出价格,那么利润就是卖出价格-最低价格,最次也就是0,也就是我更新了最低价格还以最低价格卖出去了,因为不能用之前的价格卖,此时利润也要相应的更新,大于保存的最大利润我们就更新,遍历完成后得到结果。

class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        if(len(prices) <= 1):
            return 0
        buy_price = prices[0]
        max_profit = 0
        for i in range(1,len(prices)):
            buy_price = min(buy_price, prices[i])
            max_profit = max(max_profit, prices[i] - buy_price)
        return max_profit
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

122题是说不限制买卖股票的次数,只要保证你卖的日期晚于买的日期即可。这个就适合用贪心算法,只要当前比前一天的大,那么我们就卖了股票。

class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        maxpro = 0
        for i in range(1,len(prices)):
            if prices[i] > prices[i-1]:
                maxpro += prices[i] - prices[i-1]
        return maxpro
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

123是由121演变而来的,原来是只能有一次,现在是可以有两次,这里有要求是说你不能买一次再买一次然后卖出去两次,只能买卖买卖。这个做法就比较有趣了,是将天数分开,前i天调用一次121的算法,后面的天调用一次121的算法,但是要注意如果外层循环i,里面再循环121的算法,会超时,这时我们考虑用两个数组来存储结果,pre_profit和pro_profit,其中pre_profit[i]表示i天之前的最大利润,pro_profit[i]表示i天之后的最大利润,前i天的很好理解和121一样的写法,后i天注意要从后往前动态规划。

class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        n = len(prices)
        if(n<2):
            return 0
        pre_max_profit = [0 for i in range(n)]
        pro_max_profit = [0 for i in range(n)]
        max_profit = 0
        pre_min_buy = prices[0]
        for i in range(1,n):
            #pre i days
            pre_min_buy = min(pre_min_buy,prices[i])
            pre_max_profit[i]=max(pre_max_profit[i-1], prices[i]-pre_min_buy)

        pro_max_sell = prices[n-1]
        for k in range(n-2,-1,-1):
            pro_max_sell = max(pro_max_sell,prices[k])
            pro_max_profit[k]=max(pro_max_profit[k+1], pro_max_sell-prices[k])
        for j in range(0,n):
            max_profit = max(max_profit,pre_max_profit[j]+pro_max_profit[j])

 

posted @ 2018-04-12 22:09  月夜_1  阅读(152)  评论(0)    收藏  举报