Skip to content

Commit 9cf1e55

Browse files
committed
Added the tests for coinChangeMin function
1 parent 2ee9eb9 commit 9cf1e55

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed

Dynamic-Programming/CoinChange.js

+16
Original file line numberDiff line numberDiff line change
@@ -15,3 +15,19 @@ export const change = (coins, amount) => {
1515
}
1616
return combinations[amount]
1717
}
18+
/**
19+
* @params {Array} coins
20+
* @params {Number} amount
21+
*/
22+
export const coinChangeMin = (coins, amount) => {
23+
const map = { 0: 1 }
24+
for (let i = 1; i <= amount; i++) {
25+
let min = Infinity
26+
for (const coin of coins) {
27+
if (i < coin) continue
28+
min = Math.min(min, 1 + map[i - coin])
29+
}
30+
map[i] = min
31+
}
32+
return map[amount] === Infinity ? -1 : map[amount] - 1
33+
}
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,44 @@
1-
import { change } from '../CoinChange'
1+
import { change, coinChangeMin } from '../CoinChange'
22

33
test('Base Case 1', () => {
44
const coins = [2, 3, 5]
55
const amount = 0
66
expect(change(coins, amount)).toBe(1)
7+
expect(coinChangeMin(coins, amount)).toBe(0)
78
})
89
test('Base Case 2', () => {
910
const coins = []
1011
const amount = 100
1112
expect(change(coins, amount)).toBe(0)
13+
expect(coinChangeMin(coins, amount)).toBe(-1)
1214
})
1315
test('Test Case 1', () => {
1416
const coins = [2, 4, 5]
1517
const amount = 12
1618
expect(change(coins, amount)).toBe(5)
19+
expect(coinChangeMin(coins, amount)).toBe(3)
1720
})
1821
test('Test Case 2', () => {
1922
const coins = [5, 2, 3, 7, 6, 1, 12, 11, 9, 15]
2023
const amount = 45
2124
expect(change(coins, amount)).toBe(12372)
25+
expect(coinChangeMin(coins, amount)).toBe(3)
2226
})
2327
test('Test Case 3', () => {
2428
const coins = [2]
2529
const amount = 3
2630
expect(change(coins, amount)).toBe(0)
31+
expect(coinChangeMin(coins, amount)).toBe(-1)
2732
})
2833
test('Test Case 4', () => {
2934
const coins = [3, 5, 7, 8, 9, 10, 11]
3035
const amount = 500
3136
expect(change(coins, amount)).toBe(35502874)
37+
expect(coinChangeMin(coins, amount)).toBe(46)
3238
})
3339
test('Test Case 5', () => {
3440
const coins = [10]
3541
const amount = 10
3642
expect(change(coins, amount)).toBe(1)
43+
expect(coinChangeMin(coins, amount)).toBe(1)
3744
})

0 commit comments

Comments
 (0)