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
相关推荐
想吃火锅10051 天前
【leetcode】14.最长公共前缀js
算法·leetcode·职场和发展
小林ixn1 天前
LeetCode 206. 反转链表(迭代 + 递归详解)
算法·leetcode·链表
菜鸟‍1 天前
LeetCode 1 27 和 704 || 两数之和 移除元素 二分查找
算法·leetcode·职场和发展
退休倒计时1 天前
【每日一题】LeetCode 142. 环形链表 II TypeScript
算法·leetcode·链表·typescript
sjsjs112 天前
力扣3558. 给边赋权值的方案数 I
算法·leetcode·职场和发展
花间相见2 天前
【LeetCode01】—— 无重复字符的最长子串:滑动窗口经典题详解
python·算法·leetcode
言存2 天前
力扣热题283 移动零
数据结构·算法·leetcode
洛水水2 天前
【力扣100题】80.寻找旋转排序数组中的最小值
数据结构·算法·leetcode
洛水水2 天前
【力扣100题】82.有效的括号
c++·算法·leetcode
legend050709ComeON2 天前
常见面试题-leetcode
数据结构·算法·leetcode