码迷,mamicode.com
首页 > 其他好文 > 详细

188 Best Time to Buy and Sell Stock IV

时间:2015-07-21 14:11:50      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:

188 Best Time to Buy and Sell Stock IV 

这道题是我目前为止最得意的一道题了 看看自己的运行时间已经超出所有 Python的解法 自己都醉了 

 

技术分享

class Solution:
    def __init__(self):
        self.start = 0
        self.end = 0
        self.ans = 0
        self.p = []
    
    def maxProfit(self, k, prices):
        i = 1
        if len(prices) <= 1:
            return 0
        while i < len(prices):
            self.p.append(prices[i] - prices[i-1])
            i += 1
        if k >= len(self.p):
            return sum([x for x in self.p if x > 0])
        j = 0
        while j < k:
            ret = self.getProfit()
            if ret == 0:
                return self.ans
            self.ans += ret
            self.updatePrice()
            j += 1
        return self.ans

    def getProfit(self):
        s, tmpS = 0, 0
        tmpStart = 0
        for i in range(0 ,len(self.p)):
            tmpS += self.p[i]
            if tmpS <= 0:
                tmpS = 0
                tmpStart = i + 1
            else:
                if tmpS > s:
                    self.start = tmpStart
                    self.end = i + 1
                    s = tmpS
        return s

    def updatePrice(self):
        for i in range(self.start, self.end):
            self.p[i] *= -1

 

188 Best Time to Buy and Sell Stock IV

标签:

原文地址:http://www.cnblogs.com/dapanshe/p/4664092.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!