簡単 1件解決済み 正答率100.0%

Cash: Fewest Coins

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

このチャレンジで学べること

  • 最も大きな硬貨から選ぶ
  • 除算と剰余で枚数を求める
  • 貪欲な両替が最適になる場合を知る

問題

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

使える最大の硬貨から取り、その残りを小さい硬貨で処理します。

ヒント 2

割り算と剰余を使うと、各硬貨の枚数を効率よく数えられます。

ヒント 3

ぴったりの倍数では、余りを間違えて残さないよう注意します。

目安の計算量

時間 O(1)、追加メモリ O(1)

参考資料

この課題はCodeUtility用に調整されています。上記の説明と制約に従ってください。

ランキング

全体ランキング

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

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

他の人の解答から学ぶ

コミュニティの解答

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