DataWhale task09

买卖股票的最佳时机

class Solution {
    public int maxProfit(int[] prices) {
        if(prices.length <= 1)
            return 0;
        int min = prices[0], max = 0;
        for(int i = 1; i < prices.length; i++) {
            max = Math.max(max, prices[i] - min);
            min = Math.min(min, prices[i]);
        }
        return max;
    }
}

买卖股票的最佳时机 II

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

二叉树中的最大路径和

class Solution {
    int maxm = Integer.MIN_VALUE;
    public int maxPathSum(TreeNode root) {
        compute(root);
        return maxm;
    }
    public int compute(TreeNode root){
        if(root==null) return 0;
        int sum = root.val;
        int l = compute(root.left);  
        int r = compute(root.right); 
        maxm = Math.max(maxm,sum+l+r);
        sum += Math.max(l,r);
        return Math.max(0,sum);
    }
}

你可能感兴趣的:(DataWhale task09)