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

Cash: Fewest Coins

Give change with as few U.S. coins as possible.

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

  • Pick the largest coin first
  • Use division and remainder for counts
  • See when greedy change is optimal

โจทย์

ดูฉบับแปล

A cashier gives change using quarters (25¢), dimes (10¢), nickels (5¢) and pennies (1¢). Always using the largest coin that still fits gives the fewest coins for these values. Return how many coins are needed for cents.

Implement fewest_coins(cents).

Input

cents: The change owed in cents.

Output

Return the minimum number of coins.

เงื่อนไข

0 ≤ cents ≤ 1,000,000

ตัวอย่าง

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

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

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

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

คำอธิบาย

One quarter (25), one dime (35), one nickel (40) and one penny (41): 4 coins.

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

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

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

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

คำอธิบาย

No change is owed: 0 coins.

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

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

คำใบ้ 1

Use the largest coin denomination that fits, then move to smaller coins with the remaining amount.

คำใบ้ 2

Divide and take remainders to count each coin type efficiently.

คำใบ้ 3

Be careful with exact multiples so you do not leave a leftover amount by mistake.

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

O(1) time, O(1) extra space

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

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

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

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

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