【LeetCode】力扣刷题之路 (20240304~20240308)

题目(20240304~20240308)

226. 翻转二叉树

给你一棵二叉树的根节点 root ,翻转这棵二叉树,并返回其根节点。

示例 1
在这里插入图片描述

输入:root = [4,2,7,1,3,6,9]
输出:[4,7,2,9,6,3,1]

示例 2
在这里插入图片描述

输入:root = [2,1,3]
输出:[2,3,1]

示例 3

输入:root = []
输出:[]

提示

树中节点数目范围在 [0, 100] 内
-100 <= Node.val <= 100

代码

from typing import Optional, List

# 定义二叉树节点
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


# 226.翻转二叉树
class Solution:
    # 打印二叉树
    def printTree(self, root: Optional[TreeNode]) -> List[int]:
        if not root:
            return []
        res = []
        queue = [root]
        while len(queue) > 0:
            node = queue.pop(0)
            res.append(node.val)
            if node.left:
                queue.append(node.left)
            if node.right:
                queue.append(node.right)
        return res

    # 翻转二叉树-递归
    def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        # 空树
        if not root:
            return []
        left = self.invertTree(root.left)
        right = self.invertTree(root.right)
        root.left, root.right = right, left  # 左右互换
        return root


if __name__ == "__main__":
    # 226.翻转二叉树 - 示例1
    root = TreeNode(4)
    root.left = TreeNode(2)
    root.right = TreeNode(7)
    root.left.left = TreeNode(1)
    root.left.right = TreeNode(3)
    root.right.left = TreeNode(6)
    root.right.right = TreeNode(9)  # 输入:root = [4,2,7,1,3,6,9]
    s = Solution()
    res = s.invertTree(root)
    rp = s.printTree(res)
    print(rp)  # 输出: [4,7,2,9,6,3,1]
    # 示例2
    r2 = TreeNode(2)
    r2.left = TreeNode(1)
    r2.right = TreeNode(3)  # 输入: r2 = [2,1,3]
    res2 = s.invertTree(r2)
    rp2 = s.printTree(res2)
    print(rp2)  # 输出: [2,3,1]
    # 示例3
    r3 = None  # 输入: r3 = []
    res3 = s.invertTree(r3)
    rp3 = s.printTree(res3)
    print(rp3)  # 输出: []

714. 买卖股票的最佳时机含手续费

给定一个整数数组 prices,其中 prices[i]表示第 i 天的股票价格 ;整数 fee 代表了交易股票的手续费用。你可以无限次地完成交易,但是你每笔交易都需要付手续费。如果你已经购买了一个股票,在卖出它之前你就不能再继续购买股票了。
返回获得利润的最大值。
注意:这里的一笔交易指买入持有并卖出股票的整个过程,每笔交易你只需要为支付一次手续费。

示例 1

输入:prices = [1, 3, 2, 8, 4, 9], fee = 2
输出:8
解释:能够达到的最大利润:
在此处买入 prices[0] = 1
在此处卖出 prices[3] = 8
在此处买入 prices[4] = 4
在此处卖出 prices[5] = 9
总利润: ((8 - 1) - 2) + ((9 - 4) - 2) = 8

示例 2

输入:prices = [1,3,7,5,10,3], fee = 3
输出:6

提示

1 <= prices.length <= 5 * 10^4
1 <= prices[i] < 5 * 10^4
0 <= fee < 5 * 10^4

代码

from typing import List


class Solution:
    def maxProfit(self, prices: List[int], fee: int) -> int:
        cost = prices[0] + fee  # 初始成本默认第一天买入价 + 手续费
        profit = 0  # 初始利润为0
        for i in prices:
            if i + fee < cost:  # (当天价格+手续费)低于初始成本可买
                cost = i + fee  # 成本 = 买入价 + 手续费
            elif i > cost:  # 当天价格高于成本可卖
                profit += i - cost  # 利润 = 卖出价 - 成本
                cost = i  # 完成交易后成本重置为当天的价格
        return profit


if __name__ == "__main__":
    # 714.买卖股票的最佳时机含手续费 示例1
    prices = [1, 3, 2, 8, 4, 9]
    fee = 2
    a = Solution()
    res = a.maxProfit(prices, fee)
    print(res)  # 输出:8
    # 示例2
    prices = [1, 3, 7, 5, 10, 3]
    fee = 3
    res = a.maxProfit(prices, fee)
    print(res)  # 输出:6

动态规划解法

from typing import List


class Solution:
    def maxProfit(self, prices: List[int], fee: int) -> int:
        df = [[0] * 2 for _ in range(len(prices))]  # 构造DataFrame数据结构 [[0, 0],...]
        # df[i][0]表示第i天不持有股票(未买/卖出), df[i][1]表示第i天持有股票(未卖/买入)
        df[0][0], df[0][1] = 0, - prices[0] - fee  # 定义第 0 天不持有利润为0,第 0 天持有成本则为 -prices[0] - fee,df:[[0, -prices[0]-fee],...]
        i = 0
        profit = 0
        for i in range(len(prices) - 1):
            df[i + 1][0] = max(df[i][0], df[i][1] + prices[i + 1])  # T+1 天卖出获取的最大利润
            df[i + 1][1] = max(df[i][1], df[i][0] - prices[i + 1] - fee)  # T+1 天买入获取的最大利润
            i += 1
            profit = df[i][0]  # 第i天卖出后获取最大利润
        return profit


if __name__ == "__main__":
    # 714.买卖股票的最佳时机含手续费 示例1
    prices = [1, 3, 2, 8, 4, 9]
    fee = 2
    a = Solution()
    res = a.maxProfit(prices, fee)
    print(res)  # 输出:8
    # 示例2
    prices = [1, 3, 7, 5, 10, 3]
    fee = 3
    res = a.maxProfit(prices, fee)
    print(res)  # 输出:6

  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值