Python Greedy with explanation

  • 1
    def removeKdigits(self, num, k):
            #The whole idea is to remove the peak at each iteration
            while k > 0:
                for i in xrange(0, len(num)):
                    #if length is one, then return 0
                    if len(num) == 1:
                        return "0"
                    #if the first number is greater than second then remove the fist
                    elif i == 0 and num[i] > num[i+1]:
                        num = num[1:]
                    #if the last number is greater than the second last, then remove the last number 
                    elif i == len(num) - 1 and num[i] >= num[i-1]:
                        num = num[:len(num)-1]
                    #if the middle number is less or equal to the previous one and greater than the later one, remove mid one
                    elif num[i] >= num[i-1] and num[i] > num[i+1]:
                        num = num[:i] + num[i+1:]
                k -= 1
            #remove the leading zeroes
            while(len(num) > 1 and num[0] == "0"):
                num = num[1:]
            return num

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.