121. Best Time to Buy and Sell Stock

Leetcode link

题目简介

/**
 * @param {number[]} prices
 * @return {number}
 */

题目给我们一个数字数组 prices 代表某只股票每日的价格

我们可以选择一天买入股票,选择一天卖出股票,题目希望我们得出最大的可能收益是多少

如果收益为负,则返回 0

解题思路

我们仍然使用贪心的策略,在这个题目中,我们的优势是可以随时反悔,所以我们要找到对我们最有利的返回时机

我们以 [7,1,5,3,6,4] 为例

假设我们在 7 块的时候买入了,在 1 块的时候我们意识到吃大亏了,这个时候我们需要反悔,重新选择在 1 块的时候买入

而后面股票的价格都比 1 块高,所以我们不需要反悔,只需要比较利润,在利润最高的时候出手即可

所以,我们反悔的时机点是:当后面股价比当前买入价低时,我们需要反悔

而为了避免反悔后比反悔前利润低的情况(比如 [2, 20, 1, 5]),我们需要用一个变量 profit 记录当前利润最大值

最后返回 profit 即可

Javascript

/**
 * @param {number[]} prices
 * @return {number}
 */
var maxProfit = function(prices) {
    let profit = 0
    let buyPrice = prices[0]

    for(const price of prices) {
        if(buyPrice > price) {
            buyPrice = price
        }

        profit = Math.max(profit, price - buyPrice)
    }

    return profit
};

results matching ""

    No results matching ""