Best Time to Buy and Sell Stock III - LeetCode

Best Time to Buy and Sell Stock III - LeetCode

题目:

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).


分析:

这道题目的note很重要,说明不能买两次后卖两次,只能一轮交易后才能开始另一轮,这道题目和Best Time to Buy and Sell Stock(点击打开链接)的区别就很小了,我们只要把prices进行二分,统计每部分内的最大利润然后相加进行比较就可以。需要改动的一点是,因为当我们知道了[0,n]时间内的最大利润,[0,n+1]时间内的最大利润也可以直接进行比较出来,所以我们创建两个数组来存储每一个二分的两个时间段内两个部分的最大利润。

代码:

class Solution:
    # @param prices, a list of integer
    # @return an integer
    def maxProfit(self, prices):
        if not prices or len(prices)<2:
             return 0
        maxp = [0 for i in xrange(len(prices))]
        maxn = [0 for i in xrange(len(prices))]
        self.maxSubProfit(prices,maxp,maxn)
        maxprofit = 0
        for i in xrange(len(prices)):
               maxprofit = max(maxprofit,maxp[i]+maxn[i])
        return maxprofit
    def maxSubProfit(self,prices,maxp,maxn):
        minprice = prices[0]
        for i in xrange(1,len(prices)):
                minprice = min(prices[i],minprice)
                maxp[i] = max(maxp[i-1],prices[i]-minprice)
        maxprice = prices[-1]
        for i in range(len(prices)-1)[::-1]:
                maxprice = max(prices[i],maxprice)
                maxn[i] = max(maxn[i+1],maxprice-prices[i])



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值