题目:121 买卖股票的最佳时机
来源:力扣(LeetCode) https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock/
简单的动态规划,故不作题解。
题目:122. 买卖股票的最佳时机 II
来源:力扣(LeetCode)https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-ii/
【简单】给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。设计一个算法来计算你所能获取的最大利润。你可以尽可能地完成更多的交易(多次买卖一支股票)。
注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
思路
发现规律:
- 底-高-低:则在高点卖出
- 低-高-高:等待局部最高点
- 高-低:不买入
- 一直涨没有跌:最后价格卖出
注意:为防止越界,将最后一个值单独处理。
自顶向下:执行代码
class Solution {
public int maxProfit(int[] prices) {
int right = 0;
int profit = 0,min= Integer.MAX_VALUE;
while(right<prices.length-1){
min = Math.min(min,prices[right]); //维护一个当前的最低值
if(prices[right+1]<prices[right]){ //低高低,最高点卖出
profit += prices[right]-min;
min = prices[right+1];
right +=2;
}else{ //没涨,不买入
right++;
}
}
if(right<prices.length&&min<prices[right]) //一直涨:最后价格卖出
profit += prices[right]-min;
return profit;
}
}
复杂度
时间复杂度:O( n )
空间复杂度:O(n)
题目:124. 二叉树中的最大路径和
https://leetcode-cn.com/problems/binary-tree-maximum-path-sum/
【困难】路径 被定义为一条从树中任意节点出发,沿父节点-子节点连接,达到任意节点的序列。该路径 至少包含一个 节点,且不一定经过根节点。路径和 是路径中各节点值的总和。
输入:root = [1,2,3]
输出:6
解释:最优路径是 2 -> 1 -> 3 ,路径和为 2 + 1 + 3 = 6
思路
【前序递归】
- 某节点的子序列和最大值 = 左子树的最大值(>0) + 右子树的最大值(>0)+ 该节点的值。
- 故通过递归遍历,并用全局变量记录最大值。
- 注意:传递给根节点的值应该为一个子树,因为路径不能分叉。
执行代码
class Solution {
int max = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
cycle(root);
return max;
}
public int cycle(TreeNode root) {
if(root==null)
return Integer.MIN_VALUE;
//当值大于0时,才选择该节点
int left_max = Math.max(cycle(root.left), 0);
int right_max = Math.max(cycle(root.right), 0);
//所有最大路径和,都加上了左右值和自身值
int sum = root.val + left_max + right_max;
if(sum > max)
max = sum;
//传递一条路径的值,而不是两条
return root.val + Math.max(left_max, right_max);
}
}
复杂度
时间复杂度:O( n )
空间复杂度:O( n )