代码随想录算法训练营day37|| 第七章 贪心算法

738.单调递增的数字

当且仅当每个相邻位数上的数字 x 和 y 满足 x <= y 时,我们称这个整数是单调递增的。

给定一个整数 n ,返回 小于或等于 n 的最大数字,且数字呈 单调递增 。题目

class Solution {
public:
    int monotoneIncreasingDigits(int n) {
        string strNum=to_string(n);
        int flag=strNum.size();
        for(int i=strNum.size()-1;i>0;i--){
            if(strNum[i-1]>strNum[i]){
                flag=i;
                strNum[i-1]--;
            }
        }
        for(int i=flag;i<strNum.size();i++){
            strNum[i]='9';
        }
        return stoi(strNum);
    }
};

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

给定一个整数数组 prices,其中 prices[i]表示第 i 天的股票价格 ;整数 fee 代表了交易股票的手续费用。你可以无限次地完成交易,但是你每笔交易都需要付手续费。如果你已经购买了一个股票,在卖出它之前你就不能再继续购买股票了。返回获得利润的最大值。题目

贪心算法:

class Solution {
public:
    int maxProfit(vector<int>& prices, int fee) {
        int result=0;
        int minPrice=prices[0];
        for(int i=0;i<prices.size();i++){
            if(prices[i]<minPrice){
                minPrice=prices[i];
            }
            if(prices[i]>=minPrice && prices[i]<=minPrice+fee){
                continue;
            }
            if(prices[i]>=minPrice+fee){
                result+=prices[i]-minPrice-fee;
                minPrice=prices[i]-fee;
            }
        }
        return result;
    }
};

动态规划:

class Solution {
public:
    int maxProfit(vector<int>& prices, int fee) {
        int n=prices.size();
        vector<vector<int>> dp(n,vector<int>(2,0));
        dp[0][0]-=prices[0];
        for(int i=1;i<n;i++){
            dp[i][0]=max(dp[i-1][0],dp[i-1][1]-prices[i]);
            dp[i][1]=max(dp[i-1][1],dp[i-1][0]+prices[i]-fee);
        }
        return max(dp[n-1][0],dp[n-1][1]);
    }
};

968.监控二叉树

给定一个二叉树,我们在树的节点上安装摄像头。节点上的每个摄影头都可以监视其父对象、自身及其直接子对象。计算监控树的所有节点所需的最小摄像头数量。题目

class Solution {
private:
    int result;
    int traversal(TreeNode* cur) {
        if (cur==NULL) return 2;
        int left=traversal(cur->left);   
        int right=traversal(cur->right);  
        if (left==2 && right==2) return 0;
        else if (left==0 || right==0) {
            result++;
            return 1;
        } else return 2;
    }
public:
    int minCameraCover(TreeNode* root) {
        result = 0;
        if (traversal(root) == 0) { 
            result++;
        }
        return result;
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值