【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;
    }
};
相关推荐
程序员小远1 小时前
自动化测试基础知识总结
自动化测试·软件测试·python·selenium·测试工具·职场和发展·测试用例
码云数智-大飞2 小时前
RAII 与智能指针深度拆解
java·前端·算法
Dick5072 小时前
ROS2 常用命令表
人工智能·学习·算法·机器人
apcipot_rain2 小时前
计科八股20260616(2)/面经——线性代数对称阵求n次幂、概率论最大似然估计
算法
cici158743 小时前
彩色图像模糊增强(Fuzzy Enhancement)MATLAB 实现
开发语言·算法·matlab
宝贝儿好3 小时前
【LLM】第二章:HuggingFace入门学习
人工智能·深度学习·神经网络·学习·算法·自然语言处理
凌波粒3 小时前
LeetCode--491.递增子序列(回溯算法)
数据结构·算法·leetcode
啵啵啵鱼3 小时前
数组---完
算法·排序算法
嘿黑嘿呦4 小时前
chap 8排序
算法·蓝桥杯·排序算法·软件工程