121. 买卖股票的最佳时机 leetcode-hot100

42 阅读1分钟

image.png

image.png

动态规划法

class Solution {
    public int maxProfit(int[] prices) {
        int cost = Integer.MAX_VALUE, profit = 0;
        for (int price : prices) {
            //买入取最小值
            cost = Math.min(cost, price);
            //取最大利润
            profit = Math.max(profit, price - cost);
        }
        return profit;
    }
}