算法练习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)
相关推荐
测试老哥20 分钟前
Postman环境变量设置全攻略
自动化测试·软件测试·python·测试工具·职场和发展·接口测试·postman
gsfl35 分钟前
贪心算法1
算法·贪心算法
爱吃KFC的大肥羊40 分钟前
第二次面试:C++qt开发实习生
面试·职场和发展
小猪咪piggy1 小时前
【算法】day8 二分查找+前缀和
算法
Word码1 小时前
[排序算法]希尔排序
c语言·数据结构·算法·排序算法
前端小刘哥1 小时前
解析视频直播点播平台EasyDSS在视频点播领域的技术架构与性能优势
算法
黄昏恋慕黎明1 小时前
JVM虚拟机(面试重)
jvm·面试·职场和发展
QT 小鲜肉1 小时前
【数据结构与算法基础】05. 栈详解(C++ 实战)
开发语言·数据结构·c++·笔记·学习·算法·学习方法
lingran__1 小时前
算法沉淀第七天(AtCoder Beginner Contest 428 和 小训练赛)
c++·算法
前端小刘哥1 小时前
新版视频直播点播平台EasyDSS,打通远程教研与教师培训新通路
算法