代码随想录训练营第三十七天|738.单调递增的数字,714. 买卖股票的最佳时机含手续费,968.监控二叉树,总结

738.单调递增的数字

题目链接:https://leetcode.cn/problems/monotone-increasing-digits/submissions/ 

代码:

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] < strNum[i-1])
            {
                strNum[i-1]--;
                flag = i;
            }
        }
        for(int i = flag; i < strNum.size(); i++)
        {
            strNum[i] = '9';
        }
        return stoi(strNum);
    }
};

找到最应该变成9的那个位置  如果前一个比后一个大 那就减一

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

题目链接:https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/

代码:

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

注意三种情况 第三种情况时累加 然后要注意扣除手续费,同时避免重复扣手续费  

968.监控二叉树

题目链接:https://leetcode.cn/problems/binary-tree-cameras/submissions/

代码:

class Solution {
public:
    int result;
    int DFS (TreeNode* cur)
    {
        if(cur == nullptr)
            return 2;   //被覆盖
        int left = DFS(cur->left);
        int right = DFS(cur->right);
        if(left == 2 && right == 2)
            return 0;
        if(left == 0 || right == 0)
        {
            result++;
            return 1;
        }
        if(left == 1 || right == 1)
            return 2;
        return -1;
    }
    int minCameraCover(TreeNode* root) {
        result = 0;
        if(DFS(root) == 0)
            result++;
        return result;
    }
};

这个说实话没太懂 要再看看

总结

链接:https://programmercarl.com/贪心算法总结篇.html#贪心难题

还有一道这个题:

https://programmercarl.com/0714.买卖股票的最佳时机含手续费.html

给删掉了 就先没做

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值