力扣每日一练(24-1-18)

经验一:不要把问题想复杂

Python:

python 复制代码
min_price = float('inf')
        max_profit = 0
        for price in prices:
            min_price = min(min_price, price)
            max_profit = max(max_profit, price - min_price)
        return max_profit

C#:

cs 复制代码
public int MaxProfit(int[] prices) {
    int minPrice = Int32.MaxValue;
    int maxProfit = 0;
    foreach (int price in prices) {
        minPrice = Math.Min(minPrice, price);
        maxProfit = Math.Max(maxProfit, price - minPrice);
    }
    return maxProfit;
}

一开始我想到的是引入波峰波谷的概念,但是不适用,想复杂了。

相关推荐
惊讶的猫2 分钟前
字符串- 字符串转换整数 (atoi)
数据结构·算法
@小码农35 分钟前
2025年北京海淀区中小学生信息学竞赛第一赛段试题(附答案)
人工智能·python·算法·蓝桥杯
2301_7951672036 分钟前
玩转Rust高级应用 如何让让运算符支持自定义类型,通过运算符重载的方式是针对自定义类型吗?
开发语言·后端·算法·安全·rust
laocooon52385788640 分钟前
C语言 有关指针,都要学哪些内容
c语言·数据结构·算法
多多*1 小时前
牛客周赛 Round 114 Java题解
算法
他们叫我一代大侠1 小时前
Leetcode :模拟足球赛小组各种比分的出线状况
算法·leetcode·职场和发展
Nebula_g1 小时前
C语言应用实例:硕鼠游戏,田忌赛马,搬桌子,活动选择(贪心算法)
c语言·开发语言·学习·算法·游戏·贪心算法·初学者
snakecy2 小时前
信息系统项目管理师--论文case
大数据·学习·职场和发展·区块链
AI科技星2 小时前
张祥前统一场论动量公式P=m(C-V)误解解答
开发语言·数据结构·人工智能·经验分享·python·线性代数·算法
海琴烟Sunshine2 小时前
leetcode 345. 反转字符串中的元音字母 python
python·算法·leetcode