Skip to content

Commit ef5cda9

Browse files
committed
Add problem 322 - Coin Change
1 parent 6a1f38a commit ef5cda9

File tree

2 files changed

+76
-0
lines changed

2 files changed

+76
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package dynamic_programming
2+
3+
import "math"
4+
5+
func CoinChange(coins []int, amount int) int {
6+
// Special case
7+
if len(coins) == 0 || amount < 0 {
8+
return -1
9+
}
10+
// Lookup table to store number of ways to make amount i
11+
lookup := make([]int, amount+1)
12+
for i := 1; i <= amount; i++ {
13+
lookup[i] = math.MaxInt64
14+
for _, coin := range coins {
15+
if coin <= i {
16+
difference := lookup[i-coin]
17+
if difference != math.MaxInt64 {
18+
lookup[i] = min(lookup[i], 1+difference)
19+
}
20+
}
21+
}
22+
}
23+
if lookup[amount] == math.MaxInt64 {
24+
return -1
25+
}
26+
return lookup[amount]
27+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
package dynamic_programming_test
2+
3+
import (
4+
"testing"
5+
6+
"github.com/anirudhology/leetcode-go/problems/dynamic_programming"
7+
)
8+
9+
func TestCoinChange(t *testing.T) {
10+
// Test case for null coins array
11+
if result := dynamic_programming.CoinChange(nil, 5); result != -1 {
12+
t.Errorf("Expected -1, got %d", result)
13+
}
14+
15+
// Test case for empty coins array
16+
if result := dynamic_programming.CoinChange([]int{}, 5); result != -1 {
17+
t.Errorf("Expected -1, got %d", result)
18+
}
19+
20+
// Test case for negative amount
21+
if result := dynamic_programming.CoinChange([]int{1, 2, 5}, -5); result != -1 {
22+
t.Errorf("Expected -1, got %d", result)
23+
}
24+
25+
// Test case for amount 0
26+
if result := dynamic_programming.CoinChange([]int{1, 2, 5}, 0); result != 0 {
27+
t.Errorf("Expected 0, got %d", result)
28+
}
29+
30+
// Test case for amount that can't be reached
31+
if result := dynamic_programming.CoinChange([]int{2}, 3); result != -1 {
32+
t.Errorf("Expected -1, got %d", result)
33+
}
34+
35+
// Test case for amount with exact coin matches
36+
if result := dynamic_programming.CoinChange([]int{1, 2, 5}, 5); result != 1 {
37+
t.Errorf("Expected 1, got %d", result)
38+
}
39+
40+
// Test case for amount with no exact match but can be reached
41+
if result := dynamic_programming.CoinChange([]int{1, 2, 5}, 11); result != 3 {
42+
t.Errorf("Expected 3, got %d", result)
43+
}
44+
45+
// Test case for large amount
46+
if result := dynamic_programming.CoinChange([]int{1, 2, 5}, 100); result != 20 {
47+
t.Errorf("Expected 20, got %d", result)
48+
}
49+
}

0 commit comments

Comments
 (0)