【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;
    }
};
相关推荐
geovindu2 小时前
python:Logistic Regression
开发语言·后端·python·算法
geovindu3 小时前
python: Random Forest
开发语言·后端·python·算法·随机森林
.道阻且长.4 小时前
Linux基础IO:理解文件以及回顾C文件接口
linux·运维·服务器·c语言·开发语言·职场和发展
凌冰_4 小时前
数据结构 - 线性结构(三)
java·数据结构·算法·软件工程
拂拉氏4 小时前
【知识讲解】 数据结构与算法-树状数组的认识
数据结构·算法·树状数组
技术管理手帐5 小时前
【质量管理】FMEA 不是填表游戏:DFMEA 与 PFMEA 的正确打开方式
程序人生·职场和发展·软件工程·创业创新·敏捷流程
饮水桶_T6 小时前
C++ STL00 | 六大核心组件协作框架 笔记
开发语言·算法·百度·facebook·新浪微博
饮水桶_T9 小时前
Java调用大语言模型、多轮对话 笔记
笔记·算法·设计模式·电脑·ai编程
AAA修煤气灶刘哥9 小时前
QQ 音乐怎么在 25 毫秒内,决定一句话该交给谁?
人工智能·算法·llm