ปานกลาง 0 ข้อที่แก้แล้ว อัตราผ่าน 0%

Subtract Digits to Reach Zero

Use as few digit subtractions as possible to reach zero.

สิ่งที่คุณจะได้เรียนรู้

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

โจทย์

ดูฉบับแปล

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.

เงื่อนไข

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

ตัวอย่าง

ตัวอย่างที่ 1
อินพุต:
n = 14

ผลลัพธ์ที่คาดหวัง:
expected = 3
อินพุต:
long long n = 14;

ผลลัพธ์ที่คาดหวัง:
long long expected = 3;
อินพุต:
long n = 14;

ผลลัพธ์ที่คาดหวัง:
long expected = 3;

คำอธิบาย

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

ตัวอย่างที่ 2
อินพุต:
n = 7

ผลลัพธ์ที่คาดหวัง:
expected = 1
อินพุต:
long long n = 7;

ผลลัพธ์ที่คาดหวัง:
long long expected = 1;
อินพุต:
long n = 7;

ผลลัพธ์ที่คาดหวัง:
long expected = 1;

คำอธิบาย

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

แนวทางการแก้

ลองทำเองก่อน แล้วค่อยเปิดคำใบ้ทีละข้อ

คำใบ้ 1

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

คำใบ้ 2

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

คำใบ้ 3

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

ความซับซ้อนที่คาดหวัง

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

แหล่งอ้างอิง

โจทย์นี้ปรับให้เหมาะกับ CodeUtility กรุณาทำตามคำชี้แจงและข้อจำกัดด้านบน

เรียนรู้จากคนอื่น

แนวทางจากชุมชน

ยังไม่มีวิธีทำที่เผยแพร่ ลองแก้โจทย์นี้เพื่อแชร์วิธีแรก