算法练习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)
相关推荐
青 春 记 忆23 分钟前
LeetCode 283. 移动零|Python 解法详解
python·算法·leetcode
Hrain-AI1 小时前
企业 AI 治理运营怎么做:分级授权、Token 用量可观测与模型统一纳管
大数据·人工智能·算法
剑指offer.1 小时前
Linux多任务-线程篇
java·jvm·算法
nike0good2 小时前
CF 126B(Password-z algorithm/exkmp)
开发语言·c++·算法
无定义_2 小时前
Bellman-Ford——贝尔曼福特算法
数据库·算法
程序员-Benothing2 小时前
数据库的脏读、不可重复读和幻读:从面试标准答案到源码级原理
数据库·面试·职场和发展
程序员小远3 小时前
接口测试知识总结
自动化测试·软件测试·python·测试工具·职场和发展·测试用例·接口测试
HanhahnaH3 小时前
各数据结构操作的时间复杂度汇总
数据结构·算法
Yzzz-F3 小时前
CF2023D
c++·算法·dp
小小帅呀3 小时前
学习 VLA 第6天:SWIN VIT算法原理以及复现
学习·算法