Skip to content
On this page

买卖股票的最佳时机 II

Question

给你一个整数数组 prices ,其中 prices[i] 表示某支股票第 i 天的价格。

在每一天,你可以决定是否购买和/或出售股票。你在任何时候 最多 只能持有 一股 股票。你也可以先购买,然后在 同一天 出售。

返回 你能获得的 最大 利润 。

image-20230617173919571

思路

其实我们需要收集每天的正利润就可以,收集正利润的区间,就是股票买卖的区间,而我们只需要关注最终利润,不需要记录区间

那么只收集正利润就是贪心所贪的地方!

局部最优:收集每天的正利润,全局最优:求得最大利润

js
var maxProfit = function(prices) {
    let res = 0
    let fit = 0
    for(let i=1; i<prices.length; i++){
        fit =  prices[i]-prices[i-1]
        if(fit>0)
            res += fit
    }
    return res
};