算法练习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 n with 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。

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. 算法练习Day28 (Leetcode/Python-贪心算法

    2024-01-06 07:54:04       38 阅读
  2. 算法练习Day25 (Leetcode/Python-贪心算法

    2024-01-06 07:54:04       34 阅读
  3. 算法练习Day26 (Leetcode/Python-贪心算法

    2024-01-06 07:54:04       42 阅读
  4. 算法练习Day27 (Leetcode/Python-贪心算法

    2024-01-06 07:54:04       32 阅读
  5. 贪心算法练习day.5

    2024-01-06 07:54:04       10 阅读
  6. 算法训练营day28(补), 贪心算法2

    2024-01-06 07:54:04       32 阅读
  7. Day27- 贪心算法part01

    2024-01-06 07:54:04       33 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-01-06 07:54:04       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-01-06 07:54:04       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-01-06 07:54:04       19 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-01-06 07:54:04       20 阅读

热门阅读

  1. ‘str‘ object has no attribute ‘capabilities‘

    2024-01-06 07:54:04       40 阅读
  2. TwinCAT 3 tcp程序

    2024-01-06 07:54:04       35 阅读
  3. Leetcode 993. Cousins in Binary Tree (二叉树遍历好题)

    2024-01-06 07:54:04       28 阅读
  4. dplayer播放hls格式视频并自动开始播放

    2024-01-06 07:54:04       65 阅读
  5. 金蝶接口调用步骤

    2024-01-06 07:54:04       33 阅读
  6. 网页多文件合并下载成zip

    2024-01-06 07:54:04       44 阅读
  7. Micropython的包管理

    2024-01-06 07:54:04       45 阅读
  8. this的使用(js的问题)

    2024-01-06 07:54:04       40 阅读