代码随想录刷题第37天

代码随想录刷题第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;

    }

};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值