算法练习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)
相关推荐
OOJO5 分钟前
c++---list介绍
c语言·开发语言·数据结构·c++·算法·list
别或许2 小时前
1、高数----函数极限与连续(知识总结)
算法
派大星~课堂2 小时前
【力扣-142. 环形链表2 ✨】Python笔记
python·leetcode·链表
田梓燊2 小时前
code 560
数据结构·算法·哈希算法
笨笨饿2 小时前
29_Z变换在工程中的实际意义
c语言·开发语言·人工智能·单片机·mcu·算法·机器人
kobesdu2 小时前
综合强度信息的激光雷达去拖尾算法解析和源码实现
算法·机器人·ros·slam·激光雷达
weixin_413063212 小时前
记录 MeshFlow-Online-Video-Stabilization 在线稳像
算法·meshflow·实时防抖
会编程的土豆3 小时前
【数据结构与算法】动态规划
数据结构·c++·算法·leetcode·代理模式
炘爚3 小时前
深入解析printf缓冲区与fork进程复制机制
linux·运维·算法
迈巴赫车主4 小时前
蓝桥杯19724食堂
java·数据结构·算法·职场和发展·蓝桥杯