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.
具体地,求first的时候,从左向右,maintain一个当前最低价格,每次计算更新maxProfit; 求second的时候,从右向左,maintain一个当前maxPrice,每次更新maxProfit;
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if not prices: return 0
first = [0] * len(prices)
second = [0] * len(prices)
# 计算first
minPrice = prices[0]
for i in range(1, len(first)):
minPrice = min(minPrice, prices[i])
first[i] = max(first[i - 1], prices[i] - minPrice)
# 计算second
maxPrice = prices[-1]
second[-1] = 0
for i in range(len(prices) - 2, -1, -1):
maxPrice = max(maxPrice, prices[i])
second[i] = max(second[i + 1], maxPrice - prices[i])
# 计算结果
ret = 0
for i in range(len(prices) - 1):
ret = max(ret, first[i] + second[i])
return ret