Leetcode习题买卖股票最佳时期,二叉树最大路径和

买卖股票的最佳时期

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        inf=int(1e9)
        minprice=inf
        maxProfit=0

        for prices in prices:
            maxProfit=max(prices-minprice,maxProfit) #动态规划,遍历边更新边求差值
            minprice=min(prices,minprice) #遍历更新最低点
        return maxProfit

买卖股票的最佳时期II

class Solution:
#策略是所有上涨交易日都买卖(赚到所有利润),所有下降交易日都不买卖(永不亏钱)
    def maxProfit(self, prices: List[int]) -> int:
        profit=0
        for i in range(1,len(prices)):
            tmp=prices[i]-prices[i-1]
            if tmp>0: profit+=tmp
        return profit

二叉树中的最大路径和

class Solution:
    def __init__(self):
        self.maxSum=float("-inf")

    def maxPathSum(self, root: TreeNode) -> int:
        def maxGain(node):
            if not node:
                return 0 #如果没有叶子,就返回0

            leftGain=max(maxGain(node.left),0) #左节点的最大值(<0不考虑)
            rightGain=max(maxGain(node.right),0) 

            NewPath=node.val+leftGain+rightGain #路径和

            self.maxSum=max(self.maxSum,NewPath) #动态递归更新最大值

            return node.val+max(leftGain,rightGain)

        maxGain(root)
        return self.maxSum
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值