代码随想录刷题第37天
单调递增的数字
/*
* @lc app=leetcode.cn id=738 lang=cpp
*
* [738] 单调递增的数字
*
* https://leetcode.cn/problems/monotone-increasing-digits/description/
*
* algorithms
* Medium (50.33%)
* Likes: 337
* Dislikes: 0
* Total Accepted: 80.7K
* Total Submissions: 160.4K
* Testcase Example: '10'
*
* 当且仅当每个相邻位数上的数字 x 和 y 满足 x <= y 时,我们称这个整数是单调递增的。
*
* 给定一个整数 n ,返回 小于或等于 n 的最大数字,且数字呈 单调递增 。
*
*
*
* 示例 1:
*
*
* 输入: n = 10
* 输出: 9
*
*
* 示例 2:
*
*
* 输入: n = 1234
* 输出: 1234
*
*
* 示例 3:
*
*
* 输入: n = 332
* 输出: 299
*
*
*
*
* 提示:
*
*
* 0 <= n <= 10^9
*
*
*/
// @lc code=start
#include <vector>
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
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);
}
};
// @lc code=end
买卖股票的最佳时机含手续费
class Solution {
public:
int maxProfit(vector<int>& prices, int fee) {
int result = 0;
int minPrice = prices[0]; // 记录最低价格
for (int i = 1; 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;
}
};