LeetCode热题100道-Day04

10,860 阅读1分钟

LeetCode热题100道-Day04

121. 买卖股票的最佳时机

  • 遍历数组,min记录前i个值的最小值,profit记录第i个值和最小值的差值与之前的profit之间的最大值。
class Solution {
    public int maxProfit(int[] prices) {
        
        int min = prices[0]; //前i个值的最小值
        int profit = 0; //最大利润
        for(int i = 1; i < prices.length;i++){
            profit = Math.max(profit,prices[i]-min);
            min = Math.min(min,prices[i]);
        }
        return profit;
    }
}
func maxProfit(prices []int) int {
    profit := 0    //最大利润
    min := prices[0]  //前i个值的最小值
    for _,v := range prices{
        if v-min > profit{
            profit = v - min
        }
        if v < min{
            min = v
        }
    }
    return profit
}