Back to challenges
Medium 0 solved 0% acceptance

Subtract Digits to Reach Zero

Use as few digit subtractions as possible to reach zero.

What you'll learn

  • Model a process as states and moves
  • Compute the minimum steps to zero
  • Compare DP with a greedy shortcut

Problem

At each step, choose a nonzero decimal digit currently present in the number and subtract that digit. Digits are taken from the new value after every step. Find the minimum number of steps needed to reach zero.

Implement removing_digits(n).

Input

n: The positive starting number.

Output

Return the fewest subtraction steps.

Constraints

1 ≤ n ≤ 1,000,000. Subtracting zero is not a useful move and is excluded.

Examples

Example 1
Input:
n = 14

Expected output:
expected = 3
Input:
long long n = 14;

Expected output:
long long expected = 3;
Input:
long n = 14;

Expected output:
long expected = 3;

Explanation

14 → 10 → 9 → 0 uses three steps. Neither possible first subtraction can reach zero in only two steps.

Example 2
Input:
n = 7

Expected output:
expected = 1
Input:
long long n = 7;

Expected output:
long long expected = 1;
Input:
long n = 7;

Expected output:
long expected = 1;

Explanation

Subtract the only digit, 7, to reach 0 immediately.

How to approach it

Try on your own first, then open one hint at a time.

Hint 1

Each number depends on the best answer for smaller numbers reachable by subtracting one digit.

Hint 2

Dynamic programming over all values up to n avoids repeated work.

Hint 3

Remember that the available digits change after every subtraction, and zero is never a valid choice.

Expected complexity

O(n * d) time, O(n) extra space

References

This challenge is adapted for CodeUtility. Follow the statement and constraints above.

Learn from others

Community solutions

No published solutions yet. Solve this challenge to share the first one.