簡単 1件解決済み 正答率100.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つずつ開いてみましょう。

ヒント 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用に調整されています。上記の説明と制約に従ってください。

ランキング

全体ランキング

コーダーごとのいちばん良い合格解答です。速く、メモリが少なく、評価が高い解答ほど上位になります。

# コーダー 言語 時間 メモリ AI 評価 解答
1 HJhettory Jurash Python 873 ms - 4/5 コードを見る

他の人の解答から学ぶ

コミュニティの解答

ネタバレ注意: この下に解答が1件あります まずは自分で挑戦してみましょう。他の開発者のコードやAIレビューも見ることができます。 サインインして課題を解くと議論に参加できます。