Problem Description
Given two integers num and k, determine the minimum number of positive integers (where each integer ends with the digit k) that sum up to num. If it is impossible to form such a set, return -1. The sum of an empty set is 0.
Key Insights
- A valid number in the set is of the form 10*m + k for some non-negative integer m. (Note: if k is 0, the smallest positive number is 10.)
- The total sum with n numbers can be expressed as: n*k + 10 * (sum of some non-negative integers).
- Taking modulo 10 on the equation gives: (n*k) mod 10 must equal (num mod 10).
- For k ≠ 0, only n in [1, 10] need to be examined because of the periodicity in modulo 10.
- Special handling is required when num is 0 or k is 0.
Space and Time Complexity
Time Complexity: O(1) - We only check a fixed number of possible n values. Space Complexity: O(1) - Constant amount of extra space is used.
Solution
The solution involves:
- Handling the special case where num is 0, returning 0.
- Handling the case when k is 0:
- If num is non-zero and a valid candidate (i.e. ends in 0), we can take num itself if it is a valid positive number with units digit 0; otherwise, return -1.
- For k ≠ 0, iterate over possible set sizes n from 1 to 10.
- For each n, check if nk is not more than num and (num - nk) is divisible by 10.
- Return the first valid n as the minimum count.
- If no valid n is found, return -1.
The algorithm mainly uses a simple loop and modulus arithmetic to determine if a representation is possible.