买卖股票的最佳时期
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
leftGain=max(maxGain(node.left),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