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
相关推荐
aqiu11111119 小时前
【LeetCode 902】最大为 N 的数字组合 - 详细题解与数位组合思路
数据结构·算法·leetcode·蓝桥杯·数位dp
辰烨chenye20 小时前
LeetCode Hot 100 题解 · 哈希篇
算法·leetcode·哈希算法
玖玥拾21 小时前
LeetCode 219 存在重复元素 II
算法·leetcode·哈希算法·散列表
a187927218311 天前
【算法】动态规划第四篇:背包收官——min 哨兵、计数世界与组合排列分水岭
算法·leetcode·动态规划·dp·01背包·算法讲解·决策合并
辰烨chenye1 天前
LeetCode Hot 100 题解 · 子串篇
算法·leetcode·职场和发展
辰烨chenye1 天前
LeetCode Hot 100 题解 · 堆篇
java·算法·leetcode
sylviiiiiia1 天前
leetcode hot 100
python·算法·leetcode
wabs6661 天前
关于二叉树【力扣199.二叉树的右视图的思考】
数据结构·c++·算法·leetcode·二叉树·层序遍历
a187927218311 天前
【算法】动态规划第三篇:背包第一课——贪心之死与正序倒序开关
算法·leetcode·动态规划·贪心·dp·暴力·算法讲解