Leetcode121 - 123 (dp problems)

121. Best Time to Buy and Sell Stock

problem:

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 prof

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)

thingking:

可以把这个问题想象的非常简单,简单地用数学语言描述就是:

    If max{aj-ai }(j>i) > 0:
         Return  max{aj - ai }
    Else  return 0

其实这不够简单。这样来想: 把股票的波动看做是一个二维平面上连绵起伏的高山。你只能从左到右向上爬。这个问题中,你只有一次选择爬山起始点的机会,这个问题就可以归结为:怎么样才能使你一次爬山的相对海拔最高。
最价格数组进行扫描,每一次考察一个点a[i],我都去看看prices[0:i]中最矮的点海拔是多少(就成为valley吧)max{a[i] -valley} i = 1 to (len(prices) - 1 ) 就是最大的相对海拔。

Code:

class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        # dp[i] is the min element in prices[0:i]
        if len(prices) == 0:
            return 0
        dp = list(prices)
        max_dis = -1
        size = len(prices)
        for i in range(1,size):
            if dp[i] < dp[i-1]:
                pass
            else:
                dp[i] = dp[i-1]
            if prices[i] - dp[i-1] > max_dis:
                max_dis = prices[i] - dp[i-1]
        if max_dis <= 0 :
                return 0
        else:
            return max_dis

122. Best Time to Buy and Sell Stock II

Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

Thinking:

相对于上面的问题,这个问题事实上就是: 你可以买多次,但是你的手中每次最多只能有一只股票。
这个问题同样可以用爬山问题进行类比。有一片二维平面中高低起伏的山脉,你只能从左到右爬。当你爬到一个顶点之后。你可以在你的右侧的山脉中选择一个点继续往上爬。。直到山脉的尽头。求: 总共爬山高度的最大值。
考察每一个点的时候,如果这个点是山顶,减去左侧山谷的高度,加到最后值中,山顶变山谷,往后移动(山谷不是一成不变的,山谷必须是上次爬到的山顶之后的山谷)
简单地说就是把这样图形的红色部分的相对高度加总

Paste_Image.png

Code:

class Solution(object):
    def isPeak(self, li, pos):
        flag = True
        size = len(li)
        if pos < 1 or size < 1:
            flag = False
        elif pos == size - 1 and li[pos] > li[pos - 1]:
            flag = True
        elif li[pos] > li[pos-1] and li[pos] >= li[pos + 1]:
            flag = True
        return flag
    
    
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        size = len(prices)
        if size == 0:
            return 0
        valley = prices[0]
        max_profit = 0
        for i in xrange(1,size):
            if prices[i] < vally:
                valley = prices[i]
            if self.isPeak(prices, i):
                max_profit += (prices[i] - valley)
                valley = prices[i]
        return max_profit

123 Best Time to Buy and Sell Stock III

Leetcode 123
这才是boss 题,题目的难度比前面两道题大的多。题目的意思就是,你最多可以买两支股票,但是你的手上每一时刻最多只能持有一支股票,你该怎么买,才能使得收益最大?

Thinking

就像第一题中分析的那样,找到一支收益最大的股票非常容易,买两支股票收益最大化,一定会和收益最大的那支股票相关:
如果收益最大的一支股票出现在prices[left, right]这个区间,即prices[right] - prices[left]是最大的一笔收入
这样进行记录:

   [ans,left,right] = maxSingeleProfit(prices)
   # 这个函数就是表示在prices这个数据下最大的单笔股票交易收入

那么两只股票的最大收入就有三种可能:

[ans, left, right] = maxSingleProfit(prices)
# 1 left 买,right时卖, 又在买这个股票之前买了一笔
max1 = ans + maxSingleProfit(prices[:left])
# 2 left 买,right时卖 , 又在卖这个股票之后买了一笔
max2 = ans + maxSingleProfit(prices[right+1 : ])
# left处买,中间卖了一次,又在某一天买了,最后在right 又卖了这支股票
max3 = twoStepBuy(prices[left:right+1])
real_max = max(max1, max2, max3)

Codes

class Solution(object):
    def maxSingleProfit(self, prices):
        '''
        :param prices:
        :return: [ans, left, right]: buy at prices[left] and
        sell at prices[right] we can get maxSingleProfit ans.
        '''
        size = len(prices)
        left = 0
        right = size - 1
        if size <= 1:
            return [0, 0, 0]
        valley = prices[0]
        valley_index = 0
        ans = 0
        for i in xrange(1, size):
            if prices[i] < valley:
                valley = prices[i]
                valley_index = i
            if prices[i] - valley > ans:
                ans = prices[i] - valley
                right = i
                left = valley_index
        return [ans, left, right]

    def Peaks(self,prices):
        size = len(prices)
        if size <= 1:
            return []
        ans = []
        for i in range(1, size - 1):
            if prices[i] > prices[i-1] and prices[i] >= prices[i+1]:
                ans.append(i)
        return ans

    def twoStepBuy(self,prices):
        size = len(prices)
        if size <= 2:
            return 0
        peaks = self.Peaks(prices)
        left = 0
        right = len(prices) - 1
        max_profit = prices[right] - prices[left]
        for peak_id in peaks:
            tmp = self.maxSingleProfit(prices[peak_id:])[0]
            if ((prices[peak_id] - prices[0]) + tmp) > max_profit:
                max_profit = (prices[peak_id] - prices[0]) + tmp
        return max_profit

    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        size = len(prices)
        if size < 0:
            return 0
        tmp = self.maxSingleProfit(prices)
        max_one = tmp[0]
        left = tmp[1]
        right = tmp[2]
        max_two = max_one + max(self.maxSingleProfit(prices[0:left])[0], self.maxSingleProfit(prices[right + 1:])[0])
        return max(max_two, self.twoStepBuy(prices[left:right+1]))

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,284评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,115评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,614评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,671评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,699评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,562评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,309评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,223评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,668评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,859评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,981评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,705评论 5 347
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,310评论 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,904评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,023评论 1 270
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,146评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,933评论 2 355

推荐阅读更多精彩内容