2310. Sum of Numbers With Units Digit K

Updated: 2024-03-12
1 min read
[]

On This Page

LeetCode problem 2310

class Solution:
    def minimumNumbers(self, num: int, k: int) -> int:
        @cache
        def dfs(v):
            if v == 0:
                return 0
            if v < 10 and v % k:
                return inf
            i = 0
            t = inf
            while (x := i * 10 + k) <= v:
                t = min(t, dfs(v - x))
                i += 1
            return t + 1

        if num == 0:
            return 0
        if k == 0:
            return -1 if num % 10 else 1
        res = dfs(num)
        return -1 if res >= inf else res