算法练习Day28 (Leetcode/Python-贪心算法)

738. Monotone Increasing Digits

An integer has monotone increasing digits if and only if each pair of adjacent digits x and y satisfy x <= y.

Given an integer n, return the largest number that is less than or equal to nwith monotone increasing digits.

Example 1:

复制代码
Input: n = 10
Output: 9

Example 2:

复制代码
Input: n = 1234
Output: 1234

Example 3:

复制代码
Input: n = 332
Output: 299

思路,此题求小于给定的数值N的最大的单调递增序列。对于每个数位,从后向前遍历,但凡发现前一位N[i-1]比后一位N[i]大,能做的就是把后一位N[i]置9,前一位置N[i-1]-1。

python 复制代码
class Solution(object):
    def monotoneIncreasingDigits(self, n):
        """
        :type n: int
        :rtype: int
        """
        # convert int to string
        strNum = str(n)
        flag = len(strNum)
        for i in range(len(strNum)-1, 0, -1):
            if strNum[i] < strNum[i-1]:
                flag = i 
                strNum = strNum[:i-1] + str(int(strNum[i-1])-1) + strNum[i:]
        
        #for i in range(flag, len(strNum)):
        print(flag)
        strNum = strNum[:flag] + '9' * len( strNum[flag:]) 

        return int(strNum)
相关推荐
脑洞代码7 分钟前
20250909的学习笔记
算法
Christo37 分钟前
TFS-2003《A Contribution to Convergence Theory of Fuzzy c-Means and Derivatives》
人工智能·算法·机器学习
黑菜钟15 分钟前
代码随想录第七天|● 454.四数相加II ● 383. 赎金信 ● 15. 三数之和 18.四数之和
c++·算法·leetcode
Yingjun Mo27 分钟前
1. 统计推断-ALMOND收敛性分析
人工智能·算法·机器学习
海梨花35 分钟前
CSP认证练习题目推荐 (1)
算法·深度优先·csp
天上的光1 小时前
大模型——剪枝、量化、蒸馏、二值化
算法·机器学习·剪枝
pzx_0012 小时前
【LeetCode】14. 最长公共前缀
算法·leetcode·职场和发展
self_myth2 小时前
算法与数据结构实战技巧:从复杂度分析到数学优化
算法
songx_992 小时前
leetcode10(跳跃游戏 II)
数据结构·算法·leetcode
先做个垃圾出来………3 小时前
差分数组(Difference Array)
java·数据结构·算法