Leetcode: Best Time to Buy and Sell Stock III

来源:互联网 发布:什么是淘宝团队 编辑:程序博客网 时间:2024/06/15 20:15

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’

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
0 0
原创粉丝点击