算法练习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)
相关推荐
独自破碎E1 分钟前
【手撕真题】合并区间
算法
big_rabbit05023 分钟前
[算法][力扣110]平衡二叉树
数据结构·算法·leetcode
二年级程序员10 分钟前
排序(五)“计数排序” 与 “各排序实际用时测量”
c语言·算法·排序算法
逆境不可逃15 分钟前
【从零入门23种设计模式18】行为型之备忘录模式
服务器·数据库·设计模式·oracle·职场和发展·迭代器模式·备忘录模式
松☆17 分钟前
C++ 程序设计基础:从 Hello World 到数据类型与 I/O 流的深度解析
c++·算法
今儿敲了吗21 分钟前
41| 快速乘
数据结构·c++·笔记·学习·算法
愚者游世22 分钟前
alignof 和 alignas各版本异同
c++·学习·程序人生·职场和发展·visual studio
ysa05103024 分钟前
树的定向(dfs并查集贪心)
数据结构·c++·笔记·算法·深度优先·图论
卡梅德生物科技24 分钟前
卡梅德生物科普:CD140a(PDGFRα)靶点深度解析:机制、药物研发与未来趋势
大数据·人工智能·面试·职场和发展·学习方法
mjhcsp1 小时前
C++ A* 算法:启发式路径搜索的黄金标准
android·c++·算法