121 买卖股票的最佳时机
class Solution:
def maxProfit(self, prices: List[int]) -> int:
if not prices: return 0
n = len(prices)
dp = [[0] *2 for _ in range(n)]
dp[0][0] = 0
dp[0][1] = -prices[0]
for i in range(1,n):
dp[i][0] = max(dp[i-1][0] , dp[i-1][1] + prices[i])
dp[i][1] = max(dp[i-1][1], -prices[i])
return dp[n-1][0]
122 买卖股票的最佳时机(可以交易多次)
class Solution:
def maxProfit(self, prices: List[int]) -> int:
if not prices: return 0
n = len(prices)
dp = [[0] *2 for _ in range(n)]
dp[0][0] = 0
dp[0][1] = -prices[0]
for i in range(1,n):
dp[i][0] = max(dp[i-1][0] , dp[i-1][1] + prices[i])
dp[i][1] = max(dp[i-1][1], -prices[i])
return dp[n-1][0]
124 二叉树中的最大路径和
class Solution:
def __init__(self):
self.maxPath = float(-inf)
def maxPathSum(self, root: TreeNode) -> int:
if not root: return 0
def dfs(root):
if not root: return 0
leftMax = max(0, dfs(root.left))
rightMax = max(0, dfs(root.right))
self.maxPath = max(self.maxPath, root.val + leftMax + rightMax)
return root.val + max(leftMax, rightMax)
dfs(root)
return self.maxPath