Leetcode Task10:完成121、122、124题目并完成打卡

Task10: 完成以下三个题目并打卡(1天)

121 买卖股票的最佳时机

给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。

如果你最多只允许完成一笔交易(即买入和卖出一支股票一次),设计一个算法来计算你所能获取的最大利润。

注意:你不能在买入股票前卖出股票。

class Solution {
    public int maxProfit(int[] prices) {
        int maxprofit = 0;
        for (int i = 0; i < prices.length - 1; i++) {
            for (int j = i + 1; j < prices.length; j++) {
                int profit = prices[j] - prices[i];
                if (profit > maxprofit) {
                    maxprofit = profit;
                }
            }
        }
        return maxprofit;
    }
}

122 买卖股票的最佳时机 II

给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。

设计一个算法来计算你所能获取的最大利润。你可以尽可能地完成更多的交易(多次买卖一支股票)。

注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。

class Solution {
    public int maxProfit(int[] prices) {
        int len = prices.length;
        if (len < 2) {
            return 0;
        }

        // cash:持有现金
        // hold:持有股票
        // 状态数组
        // 状态转移:cash → hold → cash → hold → cash → hold → cash
        int[] cash = new int[len];
        int[] hold = new int[len];

        cash[0] = 0;
        hold[0] = -prices[0];

        for (int i = 1; i < len; i++) {
            // 这两行调换顺序也是可以的
            cash[i] = Math.max(cash[i - 1], hold[i - 1] + prices[i]);
            hold[i] = Math.max(hold[i - 1], cash[i - 1] - prices[i]);
        }
        return cash[len - 1];
    }
}

124 二叉树中的最大路径和

路径 被定义为一条从树中任意节点出发,沿父节点-子节点连接,达到任意节点的序列。该路径 至少包含一个 节点,且不一定经过根节点。

路径和 是路径中各节点值的总和。

给你一个二叉树的根节点 root ,返回其 最大路径和 。


class Solution {
    private int maxValue = Integer.MIN_VALUE;

    public int maxPathSum(TreeNode root) {
        maxGain(root);
        return maxValue;
    }

    private int maxGain(TreeNode root){
        if (root.left == null && root.right == null){
            maxValue = root.val > maxValue ? root.val : maxValue;
            return root.val;
        }

        int leftGain = 0;
        int rightGain = 0;
        if (root.left != null)
            leftGain = maxGain(root.left);
        if (root.right != null)
            rightGain = maxGain(root.right);

        leftGain = Math.max(leftGain, 0); // 左子树的收益:若为负则取0
        rightGain = Math.max(rightGain, 0); // // 右子树的收益:若为负则取0

        // 左-中-右情况,不能向上递归
        maxValue = leftGain+rightGain+root.val > maxValue ? leftGain+rightGain+root.val : maxValue;

        int maxGain = root.val + Math.max(leftGain, rightGain);
        // 左-中或右-中情况
        maxValue = maxGain > maxValue ? maxGain : maxValue;

        return maxGain;
    }
}
posted @ 2021-01-21 18:05  Vincy_Lemon  阅读(66)  评论(0)    收藏  举报