LeetCode热题100-买卖股票的最佳时机

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

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

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

这种题目其实一般也假定了数据会有买入和卖出点,只需要找到最低点,在最低点后如果利润大于0就假定会卖出,如果等于0就不会卖出。

python 复制代码
class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        min_price = prices[0]
        max_profit = 0

        for price in prices:
            cur_profit = price - min_price

            if cur_profit > max_profit:
                max_profit = cur_profit
            
            if price < min_price:
                min_price = price
        
        return max_profit
相关推荐
Persistent的粽子!9 小时前
双指针算法:最大盛水容器
c++·算法·leetcode
All for pursuit.16 小时前
【二叉树-10】114.二叉树展开为链表
数据结构·c++·算法·leetcode·链表
旖旎夜光7 天前
力控面试题 01.01: 判定字符是否唯一(位运算) —— 题解
c++·学习·算法·leetcode·力控
CoderYanger7 天前
A.每日一题:835. 图像重叠
java·开发语言·程序人生·leetcode·面试·职场和发展·学习方法
圣保罗的大教堂7 天前
leetcode 3524. 求出数组的 X 值 I 中等
leetcode
Tim_107 天前
【LeetCode】338、比特位计数
c++·算法·leetcode
mmmmath_37 天前
LeetCode.028.找出字符串中第一个匹配项的
数据结构·算法·leetcode
Navigator_Z7 天前
LeetCode //C - 1255. Maximum Score Words Formed by Letters
c语言·算法·leetcode
All for pursuit.7 天前
【栈-4】739.每日温度
数据结构·c++·算法·leetcode
开开心心就好7 天前
安卓手写文字生成工具,多种纸张一直免费
网络·网络协议·tcp/ip·leetcode·智能手机·电脑·模拟退火算法