121.Best Time to Buy and Sell Stock

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        length = len(prices)
        if length == 0:
            return 0
        maxProfit = 0
        minBuyPrice = prices[0]
        for i in range(length):
            if prices[i] < minBuyPrice:
                minBuyPrice = prices[i]
            else:
                maxProfit = max(prices[i]-minBuyPrice, maxProfit)
        return maxProfit

Java 版:

  • 用一个值记录前面的最小值,当前值比最小值更小时,则更新最小值;
  • 否则,计算当前卖出是否能获得更大的利润。

class Solution {
    public int maxProfit(int[] prices) {
        int minPrice = Integer.MAX_VALUE; //初始设置得足够大
        int res = 0;
        for(int i = 0; i < prices.length; i++){
            if(prices[i] < minPrice) minPrice = prices[i];//更新最小值
            else res = Math.max(res, prices[i] - minPrice); //每一次都计算利润是否更大
        }
        return res;
    }
}
原文地址:https://www.cnblogs.com/luo-c/p/12857355.html