算法练习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的最大的单调递增序列。对于每个数位,从后向前遍历,但凡发现前一位Ni-1比后一位Ni大,能做的就是把后一位Ni置9,前一位置Ni-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)
相关推荐
起个破名想半天了1 小时前
算法与数据结构之DFS深度优先遍历
数据结构·算法·深度优先
李伟_Li慢慢1 小时前
凸包算法
人工智能·算法
徐礼昭|商派软件市场负责人1 小时前
AI Agent 蜂群协作与经验基因化:从单体执行到自组织系统的工程路径
大数据·人工智能·算法·智能体·多agent
来者皆善1 小时前
【位RAW图像处理五】任意位深位图像的中值模糊快速实现及其应用。
图像处理·人工智能·算法
happyprince1 小时前
第三观 · 深刻不忘观 —— AngelSpec 哲学与升华
人工智能·算法
脚踏实地皮皮晨1 小时前
003002004_WPF Panel 基类 官方类定义
开发语言·windows·算法·c#·wpf·visual studio
啊真真真2 小时前
ArgoCD:我的GitOps探索之旅与未来展望
java·算法·argocd
海绵天哥3 小时前
LeetCode Hot 100 | 链表(下)· 分组翻转与设计(C++ 题解)
c++·leetcode·链表
就改了9 小时前
Java8 日期处理(详细版)
java·python·算法
2601_9583529010 小时前
接上USB,焊上麦,通话瞬间安静——WX-0813如何用AI降噪+100dB消回音,把嘈杂通话变成“金子“般清晰
人工智能·算法·语音识别·硬件开发·语音模块·降噪消回音