LeetCode第121题: 买卖股票的最佳时机
- 使用动态规划
- 对于商家只有两种状态, 要么买入股票, 要么没买入股票
- 当买入股票时, 要么卖出股票, 要么保留
- 当没买入股票时, 要么买入, 要么观望
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
- 思路与上一题大致一样, 由于这个可以完成多笔交易, 那么需要考虑过去的利润值, 保证当前赚的钱与过去利润值和最大
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题: 二叉树中的最大路径和
- 由于是树, 可以使用使用递归
- 递归就是将大问题化解为类似的小问题求解
- 由于本树的路径和由节点控制, 我们应该考虑节点对路径的影响
- 对于根节点, 如果它的最大路径和要么是它子树的最大路径和, 要么是带有根节点的路径的和, 因此我们只需递归求出其子树的最大路径(对于叶节点, 其最大路径就是其本身), 在参考根据点的影响, 即可得出当前树的最大路径和
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)