【leetcode】121.买卖股票的最佳时机js/c++

题目

代码

这题用的贪心的思想,每遍历到一个数就去找左边的最小值和当前时刻卖出能获得的利润,如果更大就更新最大利润,没有就继续往后找,直到遍历完。

javascript 复制代码
/**
 * @param {number[]} prices
 * @return {number}
 */
var maxProfit = function(prices) {
    let min = Infinity
    let max = 0
    for (price of prices) {
        min = Math.min(min, price)
        max = Math.max(max, price - min)
    }
    return max
};

贴一个以前写c++的代码

cpp 复制代码
class Solution {
public:
    int maxProfit(vector<int>& prices) {
        vector<int>::iterator buy=prices.begin();
        vector<int>::iterator sold=prices.begin();
        int profit=0;
        while(sold!=prices.end()){
            int temp=*sold-*buy;
            if (temp>=profit){
                profit=temp;
            }
            if (*sold<*buy){
                buy=sold;
            }
            sold++;
        }
        return profit;
    }
};
相关推荐
原凉是这样的丶12 分钟前
Qwen3.8-27B 开源后,我用双 RTX 4090 跑通了:vLLM 0.27.1、128K 上下文与 MTP 实测
linux·算法
码农大叔的博客39 分钟前
golang示例:for九九乘法表
开发语言·算法·golang
手写码匠1 小时前
华为云Flexus+DeepSeek征文|Dify 多 Agent 故障演练实战:用混沌工程主动“搞破坏“,让智能体系统越炸越稳
人工智能·深度学习·算法·aigc
叠层归一研究院1 小时前
如何用程序搭建一个 AGI 种子系统(三):生长如何对接物理与数学宇宙
人工智能·python·算法·机器学习·transformer·agi
show4332 小时前
2026小程序端AI智能优化技术实践:转文字后自动纠错+润色+分段算法分析
人工智能·算法·小程序
平生不晚2 小时前
在 SVG 体系里画一条任意的线
前端·算法
Escalating_xu2 小时前
【Linux】进程信号:从产生、阻塞与递达到 sigaction、可重入与内核返回路径
linux·运维·面试·职场和发展
evans在进步2 小时前
LeetCode 198:打家劫舍——Java 动态规划详解
java·leetcode·动态规划
逆境不可逃3 小时前
LeetCode 双题:415. 字符串相加与 143. 重排链表
算法
2601_950760793 小时前
TNF-α:自身免疫疾病治疗的核心靶点与信号通路解析
人工智能·算法·蛋白