Shu-How Zの小窝

Loading...

121. 买卖股票的最佳时机

  1. 买卖股票的最佳时机
/**
 * @param {number[]} prices
 * @return {number}
 */
var maxProfit = function(prices) {
    let max=0;
    for(let i = 0; i < prices.length; i++){
        for(let j=i+1; j < prices.length; j++){
            let profit=prices[j]-prices[i];
            if(profit>max){
                max = profit;
            }
        }
    }
    return max;
};
var maxProfit = function(prices) {
    let max=0;
    let minPrice=Infinity;
    for(let i = 0; i < prices.length; i++){
        if(prices[i]<minPrice){
            minPrice=prices[i];
        }
        else if(prices[i]-minPrice>max){
            max = prices[i]-minPrice;
        }
    }
    return max;
};
let prices = [7,1,5,3,6,4]
console.log(maxProfit(prices))

…vjx

posted @ 2025-01-19 16:55  KooTeam  阅读(8)  评论(0)    收藏  举报