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