Shu-How Zの小窝

Loading...

LeetCode:122.买卖股票的最佳时机II

LeetCode:122.买卖股票的最佳时机II

math tc g4d ..

解题思路前提:上帝视角,知道未来的价格。局部最优:见好就收,见差就不动,不做任何长远打算。

解题步骤新建一个变量,用来统计总利润。遍历价格数组,如果当前价格比昨天高,就在昨天买,今天卖,否则就不交易。遍历结束后,返回所有利润之和。

/**
 * @param {number[]} prices
 * @return {number}
 */
var maxProfit = function(prices) {
    let maxProfit = 0;
    for(let i = 1; i < prices.length; i++){
        if(prices[i] > prices[i-1]){
            maxProfit +=prices[i]- prices[i-1];
        }
    }
    return maxProfit;
};
let prices = [7,1,5,3,6,4]
console.log(maxProfit(prices))

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