代码随想录算法训练营day37 | 贪心:738.单调递增的数字,714. 买卖股票的最佳时机含手续费(留给动态规划),968.监控二叉树(hard)

738.单调递增的数字

  • 第一反应是通过 n//10 和 n%10找到对应位置的digit来比较。但是这样反而增加难度,因为想要对digit进行-1或赋值9的操作不得不将n转换为string。这样空间复杂度并没有省下,倒不如直接将n转换后再操作。

class Solution:
    def monotoneIncreasingDigits(self, n: int) -> int:
        temp = list(str(n))
        for i in range(len(temp)-1, 0, -1): #第二个参数(左边界)不能为-1,因为下面 i-1需要>=0
            if int(temp[i]) < int(temp[i-1]): 
                temp[i-1] = str(int(temp[i-1])-1)
                print(temp)
                temp[i:] = '9'*(len(temp)-i)
                print(temp)
                
        return int(''.join(temp))

714. 买卖股票的最佳时机含手续费(留给动态规划),

968.监控二叉树(hard)

你可能感兴趣的:(算法,动态规划,贪心算法,leetcode,数据结构)