Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 69eb622

Browse files
ADD Coin-Change problem #62
1 parent b05e36d commit 69eb622

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

‎Medium/coin-change.cs

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
using System;
2+
using System.Linq;
3+
4+
public class Solution
5+
{
6+
private static int[] _InitializeDP(int amount)
7+
{
8+
// Set an impossible value for all amounts to indicate they haven't been solved yet
9+
int[] dp = Enumerable.Repeat(amount + 1, amount + 1).ToArray();
10+
11+
dp[0] = 0; // No coins are needed to make 0
12+
return dp;
13+
}
14+
15+
private static void _CalculateMinCoins(int[] coins, int[] dp)
16+
{
17+
for (int i = 1; i < dp.Length; i++)
18+
{
19+
foreach (int coin in coins)
20+
{
21+
if (i >= coin) // equals to (i - coin >= 0)
22+
{
23+
dp[i] = Math.Min(dp[i], 1 + dp[i - coin]);
24+
}
25+
}
26+
}
27+
}
28+
29+
private static int _GetCoinChangeResult(int[] dp, int amount)
30+
{
31+
return (dp[amount] > amount) ? -1 : dp[amount];
32+
}
33+
34+
public static int CoinChange(int[] coins, int amount)
35+
{
36+
if (coins == null || coins.Length == 0)
37+
{
38+
return -1;
39+
}
40+
41+
if (amount == 0)
42+
{
43+
return 0;
44+
}
45+
46+
int[] dp = _InitializeDP(amount);
47+
_CalculateMinCoins(coins, dp); // Calculate the minimum coins for each amount
48+
return _GetCoinChangeResult(dp, amount);
49+
}
50+
51+
public static void Main(string[] args)
52+
{
53+
int[] coins = { 1, 6, 7, 9, 11 };
54+
55+
Console.WriteLine(CoinChange(coins, 13));
56+
57+
Console.ReadKey();
58+
}
59+
}
60+

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /