经验一:不要把问题想复杂
Python:
min_price = float('inf')max_profit = 0for price in prices:min_price = min(min_price, price)max_profit = max(max_profit, price - min_price)return max_profit
C#:
public int MaxProfit(int[] prices) {int minPrice = Int32.MaxValue;int maxProfit = 0;foreach (int price in prices) {minPrice = Math.Min(minPrice, price);maxProfit = Math.Max(maxProfit, price - minPrice);}return maxProfit;
}
一开始我想到的是引入波峰波谷的概念,但是不适用,想复杂了。