【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;
    }
};
相关推荐
cc.ChenLy20 小时前
算法从入门到精通实战指南
算法
Jerry1 天前
LeetCode 160. 相交链表
算法
Jerry1 天前
LeetCode 19. 删除链表的倒数第 N 个结点
算法
金銀銅鐵1 天前
费马小定理
python·数学·算法
技术不好的崎鸣同学1 天前
[ACTF2020 新生赛]Exec 思路及解法
算法·安全·web安全
Full Stack Developme1 天前
Java LRU 与 LFU 算法及应用
java·开发语言·算法
Jerry1 天前
LeetCode 707. 设计链表
算法
C语言小火车1 天前
C++ 堆排序深度精讲:基于完全二叉树的选择排序进化,最坏情况 O(n log n) 的稳定王者
开发语言·c++·算法·排序算法·堆排序
weixin_400005601 天前
Vision-Language-Action:LMDrive双损失函数训练模块与 LangAuto 基准评测框架
人工智能·深度学习·算法·机器学习·自动驾驶