LeetCode50题第10天

LeetCode第121题: 买卖股票的最佳时机

  1. 使用动态规划
  2. 对于商家只有两种状态, 要么买入股票, 要么没买入股票
  3. 当买入股票时, 要么卖出股票, 要么保留
  4. 当没买入股票时, 要么买入, 要么观望
class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        length = len(prices)
        if length < 2:
            return 0
        result = [[0, 0] for i in range(0, length)]
        result[0][1] = -prices[0]
        for i in range(1, length):
            result[i][0] = max(result[i - 1][0], result[i - 1][1] + prices[i])
            result[i][1] = max(result[i - 1][1], -prices[i])
        return result[length - 1][0]
        

LeetCode第122题: 买卖股票的最佳时机2

  1. 思路与上一题大致一样, 由于这个可以完成多笔交易, 那么需要考虑过去的利润值, 保证当前赚的钱与过去利润值和最大
class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        length = len(prices)
        if length < 2:
            return 0
        result = [[0, 0] for i in range(0, length)]
        result[0][1] = -prices[0]
        for i in range(1, length):
            result[i][0] = max(result[i - 1][0], result[i - 1][1] + prices[i])
            result[i][1] = max(result[i - 1][1], result[i - 1][0] - prices[i])
        return result[length - 1][0]

LeetCode第124题: 二叉树中的最大路径和

  1. 由于是树, 可以使用使用递归
  2. 递归就是将大问题化解为类似的小问题求解
  3. 由于本树的路径和由节点控制, 我们应该考虑节点对路径的影响
  4. 对于根节点, 如果它的最大路径和要么是它子树的最大路径和, 要么是带有根节点的路径的和, 因此我们只需递归求出其子树的最大路径(对于叶节点, 其最大路径就是其本身), 在参考根据点的影响, 即可得出当前树的最大路径和
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def __init__(self):
        self.result = float('-inf')
    def maxPathSum(self, root: TreeNode) -> int:
        self.func(root)
        return self.result
    def func(self, root: TreeNode) -> int:
        if root == None:
            return 0
        left = max(self.func(root.left), 0)
        right = max(self.func(root.right), 0)
        path = left + right + root.val
        self.result = max(self.result, path)
        return root.val + max(left, right)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值