【Leetcode 热题 100】121. 买卖股票的最佳时机

问题背景

给定一个数组 p r i c e s prices prices,它的第 i i i 个元素 p r i c e s [ i ] prices[i] prices[i] 表示一支给定股票第 i i i 天的价格。

你只能选择 某一天 买入这只股票,并选择在 未来的某一个不同的日子 卖出该股票。设计一个算法来计算你所能获取的最大利润。

返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润,返回 0 0 0。

数据约束

  • 1 ≤ p r i c e s . l e n g t h ≤ 1 0 5 1 \le prices.length \le 10 ^ 5 1≤prices.length≤105
  • 0 ≤ p r i c e s [ i ] ≤ 1 0 4 0 \le prices[i] \le 10 ^ 4 0≤prices[i]≤104

解题过程

整体是贪心算法,思想是维护好前缀最小值,然后不断更新最大差值即可。

具体实现

java 复制代码
class Solution {
    public int maxProfit(int[] prices) {
        int min = Integer.MAX_VALUE;
        int res = 0;
        for(int price : prices) {
            res = Math.max(res, price - min);
            min = Math.min(min, price);
        }
        return res;
    }
}
相关推荐
charliejohn1 小时前
计算机考研 408 数据结构 树形查找 相关概念及计算题例题
数据结构·考研
NAGNIP6 小时前
一文搞懂机器学习中的特征降维!
算法·面试
NAGNIP7 小时前
一文搞懂机器学习中的特征构造!
算法·面试
Learn Beyond Limits7 小时前
解构语义:从词向量到神经分类|Decoding Semantics: Word Vectors and Neural Classification
人工智能·算法·机器学习·ai·分类·数据挖掘·nlp
你怎么知道我是队长7 小时前
C语言---typedef
c语言·c++·算法
Qhumaing9 小时前
C++学习:【PTA】数据结构 7-1 实验7-1(最小生成树-Prim算法)
c++·学习·算法
踩坑记录10 小时前
leetcode hot100 3.无重复字符的最长子串 medium 滑动窗口(双指针)
python·leetcode
Z1Jxxx10 小时前
01序列01序列
开发语言·c++·算法
汽车仪器仪表相关领域12 小时前
全自动化精准检测,赋能高效年检——NHD-6108全自动远、近光检测仪项目实战分享
大数据·人工智能·功能测试·算法·安全·自动化·压力测试