Open In App

PHP Program for Coin Change | DP-7

Last Updated : 09 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Write a PHP program for a given integer array of coins[ ] of size N representing different types of denominations and an integer sum, the task is to find the number of ways to make a sum by using different denominations.

Examples:

Input: sum = 4, coins[] = {1,2,3},
Output: 4
Explanation: there are four solutions: {1, 1, 1, 1}, {1, 1, 2}, {2, 2}, {1, 3}.

Input: sum = 10, coins[] = {2, 5, 3, 6}
Output: 5
Explanation: There are five solutions: {2,2,2,2,2}, {2,2,3,3}, {2,2,6}, {2,3,5} and {5,5}.

PHP Program for Coin Change using Recursion:

Recurrence Relation:

count(coins,n,sum) = count(coins,n,sum-count[n-1]) + count(coins,n-1,sum)

For each coin, there are 2 options.

  • Include the current coin: Subtract the current coin’s denomination from the target sum and call the count function recursively with the updated sum and the same set of coins i.e., count(coins, n, sum – coins[n-1] )
  • Exclude the current coin: Call the count function recursively with the same sum and the remaining coins. i.e., count(coins, n-1,sum ).

The final result will be the sum of both cases.

Base case:

  • If the target sum (sum) is 0, there is only one way to make the sum, which is by not selecting any coin. So, count(0, coins, n) = 1.
  • If the target sum (sum) is negative or no coins are left to consider (n == 0), then there are no ways to make the sum, so count(sum, coins, 0) = 0.
  • Coin Change | DP-7

Below is the Implementation of the above approach:

PHP




<?php
// Recursive PHP program for
// coin change problem.
 
// Returns the count of ways we can
// sum coins[0...n-1] coins to get sum "sum"
function coun($coins, $n, $sum)
{
     
    // If sum is 0 then there is
    // 1 solution (do not include
    // any coin)
    if ($sum == 0)
        return 1;
     
    // If sum is less than 0 then no
    // solution exists
    if ($sum < 0)
        return 0;
 
    // If there are no coins and sum
    // is greater than 0, then no
    // solution exist
    if ($n <= 0)
        return 0;
 
    // count is sum of solutions (i)
    // including coins[n-1] (ii) excluding coins[n-1]
    return coun($coins, $n - 1,$sum ) +
        coun($coins, $n, $sum - $coins[$n - 1] );
}
 
    // Driver Code
    $coins = array(1, 2, 3);
    $n = count($coins);
    echo coun($coins, $n, 5);
     
// This code is contributed by Sam007
?>


Output

5

Time Complexity: O(2sum)
Auxiliary Space: O(sum)

PHP Program for Coin Change using Dynamic Programming (Memoization) :

The above recursive solution has Optimal Substructure and Overlapping Subproblems so Dynamic programming (Memoization) can be used to solve the problem. So 2D array can be used to store results of previously solved subproblems.

Step-by-step approach:

  • Create a 2D dp array to store the results of previously solved subproblems.
  • dp[i][j] will represent the number of distinct ways to make the sum j by using the first coins.
  • During the recursion call, if the same state is called more than once, then we can directly return the answer stored for that state instead of calculating again.

Below is the implementation of the above approach:

PHP




<?php
 
function countWays($coins, $n, $sum, &$dp) {
    // Base Case
    if ($sum == 0) {
        $dp[$n][$sum] = 1;
        return 1;
    }
 
    // If the subproblem is previously calculated, return the result
    if ($n <= 0 || $sum < 0) {
        return 0;
    }
 
    if ($dp[$n][$sum] != -1) {
        return $dp[$n][$sum];
    }
 
    // Two options for the current coin
    $dp[$n][$sum] = countWays($coins, $n, $sum - $coins[$n - 1], $dp)
        + countWays($coins, $n - 1, $sum, $dp);
 
    return $dp[$n][$sum];
}
 
$tc = 1;
// Read input here if needed
 
while ($tc--) {
    $n = 3;
    $sum = 5;
    $coins = [1, 2, 3];
    $dp = array_fill(0, $n + 1, array_fill(0, $sum + 1, -1));
    $res = countWays($coins, $n, $sum, $dp);
    echo $res . PHP_EOL;
}
 
?>


Output

5

Time Complexity: O(N*sum), where N is the number of coins and sum is the target sum.
Auxiliary Space: O(N*sum)

PHP Program for Coin Change using Dynamic Programming (Tabulation):

  • Create a 2D dp array with rows and columns equal to the number of coin denominations and target sum.
  • dp[0][0] will be set to 1 which represents the base case where the target sum is 0, and there is only one way to make the change by not selecting any coin.
  • Iterate through the rows of the dp array (i from 1 to n), representing the current coin being considered.
    • The inner loop iterates over the target sums (j from 0 to sum).
      • Add the number of ways to make change without using the current coin, i.e., dp[i][j] += dp[i-1][j].
      • Add the number of ways to make change using the current coin, i.e., dp[i][j] += dp[i][j-coins[i-1]].
  • dp[n][sum] will contain the total number of ways to make change for the given target sum using the available coin denominations.

Below is the implementation of the above approach:

PHP




<?php
 
function countDistinctWays($coins, $n, $sum) {
    $dp = array_fill(0, $sum + 1, 0);
    $dp[0] = 1;
 
    for ($i = 0; $i < $n; $i++) {
        for ($j = $coins[$i]; $j <= $sum; $j++) {
            $dp[$j] += $dp[$j - $coins[$i]];
        }
    }
 
    return $dp[$sum];
}
 
$coins = [2, 5, 3, 6];
$n = 4;
$sum = 10;
echo countDistinctWays($coins, $n, $sum) . PHP_EOL;
?>


Output

5

Time complexity : O(N*sum)
Auxiliary Space : O(N*sum)

PHP Program for Coin Change using the Space Optimized 1D array:

In the above tabulation approach we are only using dp[i-1][j] and dp[i][j] etc, so we can do space optimization by only using a 1d dp array.

Step-by-step approach:

  • Create a 1D dp array, dp[i] represents the number of ways to make the sum i using the given coin denominations.
  • The outer loop iterates over the coins, and the inner loop iterates over the target sums. For each dp[j], it calculates the number of ways to make change using the current coin denomination and the previous results stored in dp.
  • dp[sum] contains the total number of ways to make change for the given target sum using the available coin denominations. This approach optimizes space by using a 1D array instead of a 2D DP table.

Below is the implementation of the above approach:

PHP




<?php
function count_1( &$coins, $n, $sum )
{
    // table[i] will be storing the number
    // of solutions for value i. We need sum+1
    // rows as the table is constructed in
    // bottom up manner using the base case (sum = 0)
    $table = array_fill(0, $sum + 1, NULl);
 
    // Base case (If given value is 0)
    $table[0] = 1;
 
    // Pick all coins one by one and update
    // the table[] values after the index
    // greater than or equal to the value
    // of the picked coin
    for($i = 0; $i < $n; $i++)
        for($j = $coins[$i]; $j <= $sum; $j++)
            $table[$j] += $table[$j - $coins[$i]];
 
    return $table[$sum];
}
 
// Driver Code
$coins = array(2, 5, 3, 6);
$n = sizeof($coins);
$sum = 10;
$x = count_1($coins, $n, $sum);
echo $x;
 
// This code is contributed
// by ChitraNayal
?>


Output

5

Time complexity : O(N*sum)
Auxiliary Space : O(sum)

Please refer complete article on Coin Change | DP-7 for more details!



Similar Reads

Create a Coin Flip using HTML, CSS & JavaScript
We will display the styled INR coin to the user and there will be a styled button (Toss Coin). We will create the entire application structure using HTML and style the application with CSS classes and properties. Here, JavaScript will be used to manage the behavior of the Coin Flip and will be used to display the dynamic result to the user. In this
4 min read
Create a Coin Flipping App using React-Native
In this article we'll create a coin flipping app using React-Native. It allows users to simulate the flip of a coin and displays the result as either "Heads" or "Tails" with a corresponding image. The user can see the count of head and tails and can even reset the score. Preview of final output : Let us have a look at how the final output will look
3 min read
Create a Coin Flipping App using ReactJS
In this article, we will build a coin flipping application. In which the user can flip a coin and get a random result from head or tails. We create three components 'App' and 'FlipCoin' and 'Coin'. The app component renders a single FlipCoin component only. FlipCoin component contains all the behind the logic. It has a default prop coin that is an
4 min read
PHP program to change date format
You are given a string which contain date and time. Date in dd/mm/yyyy format and time in 12 hrs format.You have to convert date in yyyy/mm/dd format and time in 24 hrs format. Examples: Input : $date = "12/05/2018 10:12 AM" Output : 2018-05-12 10:12:00 Input : $date = "06/12/2014 04:13 PM" Output : 2014-12-06 16:13:00 First we will convert date to
1 min read
PHP | Change strings in an array to uppercase
You are given an array of strings. You have to change all of the strings present in the given array to uppercase no matter in which case they are currently. Print the resultant array. Examples: Input : arr[] = ("geeks", "For", "GEEks") Output : Array ([0]=&gt;GEEKS [1]=&gt;FOR [2]=&gt;GEEKS) Input : arr[] = ("geeks") Output : Array ([0]=&gt;GEEKS)
2 min read
How to change the maximum upload file size in PHP ?
The maximum size of any file that can be uploaded on a website written in PHP is determined by the values of max_size that can be posted or uploaded, mentioned in the php.ini file of the server. In case of hosted server need to contact the administrator of the hosting server but XAMPP has interpreters for the scripts written in PHP and Perl. It hel
2 min read
How to change the session timeout in PHP?
In PHP, sessions are maintained to check if the user is active. When the user becomes inactive and the user forgets to logout from the web page, there is a chance of other users viewing the page causing security breach. By default, a session in PHP gets destroyed when the browser is closed. Session timeout can be customized, to make the user's page
3 min read
How to change the color of the first character of a word using PHP script?
The preg_replace() function is an in-built function that returns a word or array of words with the replacement of some content after searching the pattern. If the search pattern is not found then it will be returned unchanged. Approach: Declare a variable with a string value.Use preg_replace() function to replace the first character of every word.D
1 min read
How to Change Array Key to Lowercase in PHP ?
This article will show you how to change the array key case to lowercase using PHP. There are two approaches to changing the key case, these are: Using array_change_key_case() functionUsing foreach() and strtolower() functionsApproach 1: Using array_change_key_case() functionThe array_change_key_case() function is used to change the case of all of
2 min read
How to Change Background Image with PHP?
We are going to dynamically change background images on webpages using PHP. Incorporating a dynamic background image on a web page can improve user experience and provide personalized content based on different conditions. Below are the approaches to change the background image using PHP: Table of Content Using inline CSS and PHPUsing JavaScript an
3 min read