0. 题目
1. 单调栈,维护minx
class Solution:
def maxProfit(self, prices: List[int]) -> int:
res = 0
minx = prices[0]
for i in range(1,len(prices)):
if prices[i]<minx:
minx = prices[i]
else:
res = max(res,prices[i]-minx)
return res
2. 动态规划,状态转移
维护一对buy和sell的状态转移
int maxProfit(vector<int>& prices) {
int buy = INT_MIN, sell = 0;
for (auto& p : prices)
{
buy = max(buy, -p); // max(不买,买了)
sell = max(sell, buy + p); // max(不卖,卖了)
}
return sell;
}