【面试经典150题】买卖股票的最佳时机Ⅱ

题目链接

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

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

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

  • 1 <= prices.length <= 3 ∗ 1 0 4 3 * 10^4 3∗104
  • 0 <= pricesi <= 1 0 4 10^4 104

两种情况:

  1. 当天买当天卖,获益为0。
  2. 当天买后天卖,获益pricesj-pricesi

要想利益最大,就要保证获益pricesj-pricesi不小于0。

javascript 复制代码
/**
 * @param {number[]} prices
 * @return {number}
 */
var maxProfit = function(prices) {
	let profit=0;
    for(let i=0;i<prices.length-1;i++){
        if(prices[i+1]>prices[i]){
            profit+=(prices[i+1]-prices[i]);
        }
    }
    return profit;
};
相关推荐
索尔~古德曼2 分钟前
CF(1400-1400&1300-1500)错题集
算法
All for pursuit.1 小时前
【二分查找-2】34.在排序数组中查找元素的第一个和最后一个位置
数据结构·c++·算法·leetcode
泯泷1 小时前
为什么 AI 会"失忆"?——读懂 Agent 的记忆系统(一)
人工智能·算法·agent
战族狼魂2 小时前
AI Agent核心能力解析
面试·ai编程
DeepAgent2 小时前
AI Agent 面试篇(05):AI 面试——对着摄像头怎么答
面试·agent
需要8263 小时前
分布式 ID 生成:雪花算法、号段模式与时钟回拨
分布式·算法
垆边人似月.3 小时前
华为机考题:字符串分隔
算法·华为
CQU_JIAKE3 小时前
9.4【A】
算法
CQU_JIAKE3 小时前
9.13[A]
算法
懿路向前3 小时前
【唤醒实战笔记】2026-09-29 | 智能体提示词迭代史(v1 → v8)
linux·笔记·算法