121. 买卖股票的最佳时机 easy 贪心算法


时间复杂度:O(n),只遍历一次数组

空间复杂度:O(1),只用两个变量存储状态

买入点一旦确定,卖出价格越高利润越大

只要历史最低买入点没变,卖出价格增加时利润只会增大或者不变

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

        # buy:  最低买入点(动态更新)
        # profit: 当日卖出,根据最低买入点,可以赚多少(动态更新)

        # 只遍历一遍
        buy = float('inf')  # 最低买入点初始值,无穷大
        profit = 0    # 初始利润值,0

        for price in prices:   # 假设每一天都卖,当日卖出,根据最低买入点,可以赚多少(动态更新profit)
            
            #  最低买入点(动态更新)
            if price < buy:
                buy = price   

            # 只要最低买入点没更新,就可以算日卖出,根据最低买入点,可以赚多少
            elif price-buy > profit:   # 动态更新profit
                profit = price-buy

        return profit
                
相关推荐
Tisfy4 小时前
LeetCode 1927.求和游戏:抵消+看最值
java·leetcode·游戏·题解·博弈论
玖玥拾4 小时前
LeetCode 125 验证回文串
算法·leetcode
玖玥拾13 小时前
LeetCode 392 判断子序列
笔记·算法·leetcode
重生之后端学习14 小时前
239. 滑动窗口最大值[困难]✅
java·数据结构·算法·leetcode·职场和发展
INGNIGHT1 天前
1584.连接所有点的最小费用(最小生成树&并查集union find)
c++·leetcode
wabs6661 天前
关于二叉树【力扣144.二叉树的前序遍历的思考】
数据结构·c++·算法·leetcode·二叉树
Xin7702 天前
LeetCode 23.合并 K 个升序链表(分治递归)
leetcode
Nil2082 天前
leetcode 105从前序和中序遍历序列构造二叉树
算法·leetcode·职场和发展
Nil2082 天前
leetcode 114二叉树展开为链表
leetcode·链表·深度优先
cz07102 天前
hot100_搜索二维矩阵 II
算法·leetcode