算法60天:day37
贪心算法-单调递增的数字
class Solution {
public:
int monotoneIncreasingDigits(int n) {
string N = to_string(n);
int length = N.size();
int flag = length; //记录9开始的位置
for(int i = length - 1; i > 0; i--){
if(N[i - 1] > N[i]){
N[i - 1]--;
flag = i;
}
}
//开始将9赋值进去
for(int i = flag; i < length; i++){
N[i] = '9';
}
return stoi(N);
}
};
贪心算法-买卖股票的最佳时机含手续费
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(minPrice <= prices[i] && minPrice + fee >= prices[i]){
continue;
}
// 计算利润,可能有多次计算利润,最后一次计算利润才是真正意义的卖出
if(prices[i] > minPrice){
result += prices[i] - minPrice -fee;
minPrice = prices[i] - fee;
}
}
return result;
}
};
贪心算法-监控二叉树
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
/*
0:该节点无覆盖
1:本节点有摄像头
2:本节点有覆盖
*/
int result = 0;
int traversal(TreeNode* cur){
//空结点
if(cur == nullptr) return 2;
int left = traversal(cur->left);
int right = traversal(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) {
//情况四:根节点无覆盖
if(traversal(root) == 0){
result++;
}
return result;
}
};