LeetCode 121. 买卖股票的最佳时机

//暴力法
class Solution {
    public int maxProfit(int[] prices) {
        //边界判断
        if(prices.length < 2) {
            return 0;
        }
        //定义股票的最大收益
        int  maxprofit = 0;
        //定义最低价买入
        int min = prices[0];

        for(int i = 1;i < prices.length;i++){
            //今天的价格是不是比历史最低还要低,如果是,更新最低价格
            if(min > prices[i]){
                min = prices[i];
            }
            //比较今天的行情 和 以前最好的行情,如果今天的行情更好,更新最好的行情
            maxprofit = Math.max(maxprofit,prices[i] - min);
        }
        return maxprofit;
    }
}
原文地址:https://www.cnblogs.com/peanut-zh/p/13915088.html