算法练习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)
相关推荐
卡提西亚4 分钟前
leetcode-239. 滑动窗口最大值
算法·leetcode·职场和发展
ShallWeL27 分钟前
【机器学习】(20)—— 类别不平衡
人工智能·算法·机器学习
明志数科32 分钟前
具身智能数据标准化:从碎片化接口到统一工作组的技术路径
人工智能·算法·机器学习
旖-旎42 分钟前
LeetCode 494:目标和(动态规划/01背包问题)—— 题解
c++·算法·leetcode·动态规划·01背包
spssau1 小时前
一文学会结构方程模型:从模型搭建、路径图绘制到不达标调整,实操全流程
人工智能·python·算法
zzz_23681 小时前
【Java实习面试算法冲刺】总复盘
java·算法·面试
DFT计算杂谈1 小时前
DeepSeek 集群服务器无root本地部署指南
数据库·人工智能·python·opencv·算法
qq_454245032 小时前
GraphFoundation — 通用图基础框架
算法·架构
不一样的故事1263 小时前
军工行业合规与基础认知
数据结构·经验分享·算法
圣保罗的大教堂8 小时前
leetcode 3867. 数对的最大公约数之和 中等
leetcode