- 买卖股票的最佳时机
class Solution:
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
min_p, max_p = 999999, 0
for i in range(len(prices)):
min_p = min(min_p, prices[i])
max_p = max(max_p, prices[i] - min_p)
return max_p
122.买卖股票的最佳时机
class Solution {
public int maxProfit(int[] prices) {
int ans=0;
for(int i=1;i<=prices.length-1;i++)
{
if(prices[i]>prices[i-1])
{
ans+=prices[i]-prices[i-1];
}
}
return ans;
}
}
124.二叉树中的最大路径和
class Solution:
res = float('-inf')
def maxPathSum(self, root: TreeNode) -> int:
self.getMax(root)
return self.res
def getMax(self,root):
if not root:
return 0
# 如果子树路径和为负则应当置0表示最大路径不包含子树
left = max(0, self.getMax(root.left))
right = max(0, self.getMax(root.right))
# 以当前节点为根节点,判断在该节点包含左右子树的路径和是否大于当前最大路径和
self.res = max(self.res, root.val + left + right)
# 当前节点作为父节点的一个子节点和父节点连接的话则需取【单端的最大值】返回
return max(left, right) + root.val