mirror of
https://github.com/krahets/hello-algo.git
synced 2026-11-09 23:40:05 +08:00
* Retranslate the complete Japanese online edition from Chinese * Fit Japanese homepage labels and localize heading permalinks * Point Japanese contribution instructions to the Japanese preview * Replace locale conditionals with multilingual UI tables
56 lines
2.2 KiB
Java
56 lines
2.2 KiB
Java
/**
|
|
* File: coin_change_greedy.java
|
|
* Created Time: 2023-07-20
|
|
* Author: krahets (krahets@163.com)
|
|
*/
|
|
|
|
package chapter_greedy;
|
|
|
|
import java.util.Arrays;
|
|
|
|
public class coin_change_greedy {
|
|
/* 硬貨の両替:貪欲法 */
|
|
static int coinChangeGreedy(int[] coins, int amt) {
|
|
// coins リストはソート済みと仮定する
|
|
int i = coins.length - 1;
|
|
int count = 0;
|
|
// 残額がなくなるまで貪欲な選択を繰り返す
|
|
while (amt > 0) {
|
|
// 残額より小さく、残額に最も近い硬貨を探す
|
|
while (i > 0 && coins[i] > amt) {
|
|
i--;
|
|
}
|
|
// coins[i] を選ぶ
|
|
amt -= coins[i];
|
|
count++;
|
|
}
|
|
// 実行可能な方法が見つからなかった場合、-1 を返す
|
|
return amt == 0 ? count : -1;
|
|
}
|
|
|
|
public static void main(String[] args) {
|
|
// 貪欲法:大域的最適解が得られることを保証できる
|
|
int[] coins = { 1, 5, 10, 20, 50, 100 };
|
|
int amt = 186;
|
|
int res = coinChangeGreedy(coins, amt);
|
|
System.out.println("\ncoins = " + Arrays.toString(coins) + ", amt = " + amt);
|
|
System.out.println("目標金額 " + amt + " にするために必要な硬貨の最小枚数は " + res);
|
|
|
|
// 貪欲法:大域的最適解が得られることを保証できない
|
|
coins = new int[] { 1, 20, 50 };
|
|
amt = 60;
|
|
res = coinChangeGreedy(coins, amt);
|
|
System.out.println("\ncoins = " + Arrays.toString(coins) + ", amt = " + amt);
|
|
System.out.println("目標金額 " + amt + " にするために必要な硬貨の最小枚数は " + res);
|
|
System.out.println("実際に必要な最小枚数は 3 、すなわち 20 + 20 + 20");
|
|
|
|
// 貪欲法:大域的最適解が得られることを保証できない
|
|
coins = new int[] { 1, 49, 50 };
|
|
amt = 98;
|
|
res = coinChangeGreedy(coins, amt);
|
|
System.out.println("\ncoins = " + Arrays.toString(coins) + ", amt = " + amt);
|
|
System.out.println("目標金額 " + amt + " にするために必要な硬貨の最小枚数は " + res);
|
|
System.out.println("実際に必要な最小枚数は 2 、すなわち 49 + 49");
|
|
}
|
|
}
|