代码随想录训练营第三十七天 | 贪心算法

今天是第三十七天,贪心算法的最后一天

 

738.单调递增的数字 

class Solution {
    public int monotoneIncreasingDigits(int n) {
        String num = Integer.toString(n);
        char[] nums = num.toCharArray();
        int size = nums.length;

        if(size < 2){
            return n;
        }

        for (int i = size - 2; i>=0; i-- ){
            if(nums[i] - '0' > nums[i+1] - '0'){
                nums[i] = (char) (nums[i] - '1' + '0');
                for(int j = i+1; j< size; j++){
                    nums[j] = '9';
                }
            }
        }
        return Integer.parseInt(new String(nums));
    }
}

从后往前遍历,如果前面的数比后面的小,那就-1,然后把后面的数都变成9

714. 买卖股票的最佳时机含手续费 

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

加上手续费的买卖股票,设定一个手中股票的价格,在没卖的情况下,如果后面的价格低于当前手中的,直接替换就可以了。

如果遇到比加了手续费的手中价格还高的,那就可以卖掉了。

卖掉之后,让手上的价格减去手续费,避免交两次手续费。

 

968.监控二叉树 

class Solution {
    int res = 0;
    public int minCameraCover(TreeNode root) {
        /**
            情况4:根结点无覆盖状态,放置一个摄像头
            (1)只有根节点
            (2)左右孩子为有覆盖状态
         */
        if (minCamera(root) == 0) res++;
        return res;
    }
    /**
        后序遍历
        结点状态值
        0 本结点无覆盖
        1 本结点有摄像头
        2 本结点有覆盖
     */
    public int minCamera(TreeNode root) {
        // 空结点默认有覆盖,避免在叶子结点放摄像头
        if (root == null) return 2;
        // 遍历左右孩子
        int left = minCamera(root.left);
        int right = minCamera(root.right);
        // 情况1:若左右结点都覆盖,则本结点无覆盖
        if (left == 2 && right == 2) return 0;
        /**
            情况2:
            若左右结点存在无覆盖,则本结点放一个摄像头
            (1)left = 0, right = 0 -> 左右结点均无覆盖
            (2)left = 1, right = 0 -> 左结点有摄像头,右结点无覆盖
            (3)left = 0, right = 1 -> 左结点无覆盖,右结点有摄像头
            (4)left = 2, right = 0 -> 左结点有覆盖,右结点无覆盖
            (5)left = 0, right = 2 -> 左结点无覆盖,右结点有覆盖
         */
        else if (left == 0 || right == 0) {
            res++;
            return 1;
        }
        /**
            情况3:
            左右节点至少有一个有摄像头,则本结点是覆盖状态
            (1)left = 1, right = 2 -> 左结点有摄像头,右结点有覆盖
            (2)left = 2, right = 1 -> 左结点有覆盖,右结点有摄像头
            (3)left = 1, right = 1 -> 左右结点均有摄像头
         */
        // 左右结点存在摄像头,本结点处于覆盖状态
        else return 2;
    }
}

完全没思路

贪心算法的练习结束了,明天开始DP

 

posted @ 2022-11-18 06:43  小猫Soda  阅读(26)  评论(0)    收藏  举报