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
给删掉了 就先没做