您的位置:首页 > 其它

Leetcode: Best Time to Buy and Sell Stock III

2015-09-12 14:22 411 查看

Question

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 at most two transactions.

Note:

You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

Hide Tags Array Dynamic Programming

Hide Similar Problems (M) Best Time to Buy and Sell Stock (M) Best Time to Buy and Sell Stock II (H) Best Time to Buy and Sell Stock IV

Solution

see ‘Best Time to Buy and Sell Stock IV’

[code]class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """

        if prices==[]:
            return 0

        if 2>=len(prices):
            return self.maxprofit2(prices)

        globalv = [0]*3
        localv = [0]*3

        for i in range(1,len(prices)):
            diff = prices[i] - prices[i-1]
            for j in range(2,0,-1):
                localv[j]  = max( globalv[j-1] + max(diff,0), localv[j]+diff )
                globalv[j] = max( globalv[j], localv[j] )

        return globalv[2]

    def maxprofit2(self, prices):
        maxv = 0
        for ind in range(1,len(prices)):
            if prices[ind]>prices[ind-1]:
                maxv += prices[ind] - prices[ind-1]

        return maxv
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: