扫一遍数组,过程中维护两个值即可:一个是之前的最小值(buy),决定什么时候买.另一个是最多卖多少.
类似题目:leetcode1014
class Solution: def maxProfit(self, prices: List[int]) -> int: buy = float('inf') ret = 0 for p in prices: buy = min(p, buy) ret = max(ret, p - buy) return ret