Skip to content

Commit

Permalink
optimized coin_change (space complexity quadratic -> linear) (keon#593)
Browse files Browse the repository at this point in the history
  • Loading branch information
Mohd-3 authored and keon committed Dec 6, 2019
1 parent 9fb8ce4 commit 22818f7
Showing 1 changed file with 17 additions and 26 deletions.
43 changes: 17 additions & 26 deletions algorithms/dp/coin_change.py
Original file line number Diff line number Diff line change
@@ -1,37 +1,28 @@
"""
Problem
Given a value N, if we want to make change for N cents, and we have infinite supply of each of
S = { S1, S2, .. , Sm} valued //coins, how many ways can we make the change?
Given a value n, if we want to make change for N cents, and we have infinite supply of each of
coins = {S1, S2, .. , Sm} valued coins, how many ways can we make the change?
The order of coins doesn't matter.
For example, for N = 4 and S = [1, 2, 3], there are four solutions:
For example, for n = 4 and coins = [1, 2, 3], there are four solutions:
[1, 1, 1, 1], [1, 1, 2], [2, 2], [1, 3].
So output should be 4.
For N = 10 and S = [2, 5, 3, 6], there are five solutions:
For n = 10 and coins = [2, 5, 3, 6], there are five solutions:
[2, 2, 2, 2, 2], [2, 2, 3, 3], [2, 2, 6], [2, 3, 5] and [5, 5].
So the output should be 5.
Time complexity: O(n * m) where n is the value and m is the number of coins
Space complexity: O(n)
"""

def count(s, n):
# We need n+1 rows as the table is consturcted in bottom up
# manner using the base case 0 value case (n = 0)
m = len(s)
table = [[0 for x in range(m)] for x in range(n+1)]

# Fill the enteries for 0 value case (n = 0)
for i in range(m):
table[0][i] = 1

# Fill rest of the table enteries in bottom up manner
for i in range(1, n+1):
for j in range(m):
# Count of solutions including S[j]
x = table[i - s[j]][j] if i-s[j] >= 0 else 0

# Count of solutions excluding S[j]
y = table[i][j-1] if j >= 1 else 0
def count(coins, n):
# initialize dp array and set base case as 1
dp = [1] + [0] * n

# total count
table[i][j] = x + y

return table[n][m-1]
# fill dp in a bottom up manner
for coin in coins:
for i in range(coin, n+1):
dp[i] += dp[i-coin]

return dp[n]

0 comments on commit 22818f7

Please sign in to comment.