2182. Construct String With Repeat Limit

class Solution:
    def repeatLimitedString(self, s: str, repeatLimit: int) -> str:
        d = {}
        for char in s:
            if char in d:
                d[char] += 1
            else:
                d[char] = 1

        lst = []
        for i, e in enumerate(d):
            lst.append([-ord(e), e, d[e]])

        heapq.heapify(lst)

        ans = ""
        while lst:
            value = heapq.heappop(lst)
            count = value[2]

            minValue = min(value[2], repeatLimit)
            value[2] -= minValue
            lastChar = value[1]

            ans += value[1] * minValue            

            if count > repeatLimit:
                if not lst: break
                nextValue = heapq.heappop(lst)
                ans += nextValue[1]
                nextCount = nextValue[2]
                nextValue[2] -= 1

                if nextCount > 1:
                    heapq.heappush(lst, nextValue)
                heapq.heappush(lst, value)


        return ans