[leetcode] 121. 买卖股票的最佳时机

121. 买卖股票的最佳时机

动态规划:前i天的最大收益 = max{前i-1天的最大收益,第i天的价格-前i-1天中的最小价格}

维护两个值即可:min,ans

class Solution {
    public int maxProfit(int[] prices) {
        int min = Integer.MAX_VALUE;
        int ans = 0;

        for (int price : prices) {
            if (price < min) {
                min = price;
            } else if (ans < price - min) {
                ans = price - min;
            }
        }
        return ans;
    }
}
原文地址:https://www.cnblogs.com/acbingo/p/10285564.html