Torna alle sfide
Media 0 risolte 0% di accettazione

Subtract Digits to Reach Zero

Use as few digit subtractions as possible to reach zero.

Cosa imparerai

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

Problema

Mostra traduzione

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.

Vincoli

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

Esempi

Esempio 1
Input:
n = 14

Output atteso:
expected = 3
Input:
long long n = 14;

Output atteso:
long long expected = 3;
Input:
long n = 14;

Output atteso:
long expected = 3;

Spiegazione

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

Esempio 2
Input:
n = 7

Output atteso:
expected = 1
Input:
long long n = 7;

Output atteso:
long long expected = 1;
Input:
long n = 7;

Output atteso:
long expected = 1;

Spiegazione

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

Come affrontarlo

Prova prima da solo, poi apri un suggerimento alla volta.

Suggerimento 1

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

Suggerimento 2

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

Suggerimento 3

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

Complessità attesa

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

Riferimenti

Questa sfida è adattata per CodeUtility. Segui la traccia e i vincoli sopra.

Impara dagli altri

Soluzioni della community

Nessuna soluzione pubblicata. Risolvi questa sfida per condividere la prima.