7.5 - hard - 25

123. Best Time to Buy and Sell Stock III

AC的答案,基本的思想是,找出一个transaction在一个index之前完成可以获得的最大值,然后再找出,一个transaction在一个index之后完成可获得的最大值,只要找到这个index就可以了。但是这样做并不是DP,如果要解决at most k transaction好像这样就不行了。那道题在188,估计下周末能够做到。到时候再说。

class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        if len(prices) <= 1:
            return 0
        profit_from_left = [0 for _ in range(len(prices))]
        profit_from_right = profit_from_left[:]

        cur_min = prices[0]
        for i in range(1, len(prices)):
            profit_from_left[i] = max(0, prices[i] - cur_min, profit_from_left[i-1])
            cur_min = min(cur_min, prices[i])
                
        cur_max = prices[-1]
        for i in range(len(prices)-1)[::-1]:
            profit_from_right[i] = max(0, cur_max - prices[i], profit_from_right[i+1])
            cur_max = max(cur_max, prices[i])
        
        # print profit_from_left
        # print profit_from_right
        max_profit = 0
        for index in range(len(prices)):
            max_profit = max(profit_from_left[index]+profit_from_right[index], max_profit)
        return max_profit
                               
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,776评论 0 33
  • 198. House Robber【Easy DP】You are a professional robber p...
    GeniusYY阅读 1,163评论 0 0
  • 分治方法 将问题划分成互不相交的子问题 递归地求解子问题 将子问题的解组合起来 动态规划(两个要素:最优子结构、子...
    superlj666阅读 526评论 0 0
  • 今天开始读《金字塔原理》,这本书是讲思考表达和解决问题的逻辑,争取在四天之内读完吧! 思想的才是句子和段落要表达的...
    婉琳阅读 229评论 1 1
  • 又一期《感动中国》人物新鲜出炉,带着温度,带来感动,让我们泪流满面;如熊熊火炬,在昏昧不明的环境中引导我们寻找人生...
    蓝田玉阅读 623评论 0 8