Best time to buy and sell
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if not prices:
return 0
# 只能背过有一种 dp 的解决方案是 local max 和 global max 结合
# 这种 local global 结合的题最好的理解思路是画一个 differences 的变化图
localMax = [0] * len(prices)
globalMax = 0
for i in range(1, len(prices)):
# localMax[i] = localMax[i - 1] + max(0, prices[i] - prices[i - 1]) # 这样的话相当于只要 price 不涨,就卖掉;但其实只要 localMax[i - 1] + prices[i] - prices[i - 1] > 0,这个 localMax 所属的 minPrice 在后面的 prices 中就还有可能有更高的值。
localMax[i] = max(0, localMax[i - 1] + prices[i] - prices[i - 1])
globalMax = max(globalMax, localMax[i])
return globalMaxLast updated