#2310

Sum of Numbers With Units Digit K

Medium
MathDynamic ProgrammingGreedyEnumeration
LeetCode ↗

Approaches

💡

Intuition

Time Space

The brute force approach explores all possible combinations of integers that end with the digit k to see if they can sum up to num. This is straightforward but inefficient, as it can involve many unnecessary calculations.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a counter for the number of integers used.
  2. 2Step 2: Start from the smallest integer with units digit k and keep adding it to the sum until it exceeds num.
  3. 3Step 3: If the sum equals num, return the count of integers used; if it exceeds num, try the next larger integer with units digit k.
solution.py18 lines
1# Full working Python code
2
3def min_set_size(num, k):
4    if num == 0:
5        return 0
6    count = 0
7    current_sum = 0
8    current_number = k
9    while current_sum < num:
10        current_sum += current_number
11        count += 1
12        if current_sum == num:
13            return count
14        current_number += 10
15    return -1
16
17# Example usage
18print(min_set_size(58, 9))  # Output: 2

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.