leetcode121_买卖股票的最佳时机

public int maxProfit(int[] prices) {
    if(prices.length < 2) return 0;
    int ans = 0, beforeMin = prices[0];
    for(int i =1; i < prices.length; i++) {
        int profit = prices[i] - beforeMin;
        if( profit > 0) ans = Math.max(ans, prices[i] - beforeMin);
        beforeMin = Math.min(beforeMin, prices[i]);
    }
    return ans;
}
posted @ 2022-02-04 21:31  明卿册  阅读(20)  评论(0编辑  收藏  举报