From 9bdfcf340fca3df050bdd91f17621d5b1a64f786 Mon Sep 17 00:00:00 2001 From: Sidhant Mishra <69967446+rishi457@users.noreply.github.com> Date: Fri, 6 Oct 2023 18:36:00 +0530 Subject: [PATCH] Update coinProblem.py In this optimized version of the code, we have improved the efficiency of calculating the number of ways to make change for a given amount 'n' using a set of coin denominations specified in the 'arr' array. Let's walk through the key changes and improvements: 1. Switching to 1D Array: - We have replaced the 2D array 'table' with a 1D list called 'table'. - This change simplifies the code and reduces memory consumption because we only need to keep track of the number of ways to make change for each amount from 0 to 'n'. 2. Initialization: - We initialize 'table[0]' to 1. This represents the base case where there is one way to make change for an amount of 0, which is by not using any coins. 3. Iterative Update: - We iterate through the coin denominations in the 'arr' array and the amounts from 'S[i]' to 'n'. - For each coin denomination, we iteratively update 'table[j]' by adding 'table[j - S[i]]'. This represents the number of ways to make change for 'j' by either including the current coin denomination 'S[i]' or excluding it. By implementing these changes, we have reduced the time complexity of the code to O(n*m), where 'n' is the target amount and 'm' is the number of coin denominations. This optimization simplifies the code while making it more memory-efficient and faster for larger input values, providing a scalable solution for solving the Coin Change Problem. --- python/coinProblem.py | 31 ++++++------------------------- 1 file changed, 6 insertions(+), 25 deletions(-) diff --git a/python/coinProblem.py b/python/coinProblem.py index a2ea978..b5a0642 100644 --- a/python/coinProblem.py +++ b/python/coinProblem.py @@ -1,34 +1,15 @@ -# Dynamic Programming Python implementation of Coin -# Change problem def count(S, m, n): - # We need n+1 rows as the table is constructed - # in bottom up manner using the base case 0 value - # case (n = 0) - table = [[0 for x in range(m)] for x in range(n+1)] + table = [0] * (n + 1) + table[0] = 1 # Initialize the number of ways to make change for 0 - # Fill the entries for 0 value case (n = 0) - for i in range(m): - table[0][i] = 1 + for i in range(m): + for j in range(S[i], n + 1): + table[j] += table[j - S[i]] - # Fill rest of the table entries 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 - - # total count - table[i][j] = x + y - - return table[n][m-1] + return table[n] # Driver program to test above function arr = [1, 2, 3] m = len(arr) n = 4 print(count(arr, m, n)) - -# This code is contributed by Bhavya Jain