1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

お金の支払い 硬貨の最小枚数

1
Posted at

今回は、一円玉とX円玉、Y円玉の3種類の硬貨しかないpaiza国での支払いを計算する問題に挑戦!


問題概要

1円・X円・Y円の3種類のコインだけを使って、Z円をぴったり支払う。その時の最小の枚数を求めよ。


入力例:

50 100 855

出力例:

14




✅ OK例:

const rl = require('readline').createInterface({ input: process.stdin });

rl.once('line', (input) => {
  const [X, Y, Z] = input.split(' ').map(Number);
  let minCoins = Infinity;

  for (let i = 0; X * i <= Z; i++) {
    for (let j = 0; X * i + Y * j <= Z; j++) {
      const rest = Z - (X * i + Y * j); // 1円玉の数
      const total = i + j + rest;
      if (total < minCoins) minCoins = total;
    }
  }

  console.log(minCoins);
});
  • X円とY円硬貨をいろんな枚数で使ってみて、残りは全部1円玉。
  • すべての組み合わせを試して、いちばん少ない枚数を探している。



💡比較:if文 vs Math.min

1️⃣ if 文で書くと:

if (total < minCoins) {
    minCoins = total;
}

2️⃣ Math.min() で書くと:

minCoins = Math.min(minCoins, total);




🗒️気づきメモ

  • X * i + Y * j <= Z にして、「ピッタリ以下」だけを調べるのが大事。
  • Z - (X*i + Y*j) で残りを1円玉で計算する。(初め一円玉を忘れてたミスった)
  • 最小値の更新は minCoins = Math.min(minCoins, 新しい枚数) という書き方もある。




僕の失敗談(´;ω;`)と解決法🐈

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?