Advertisement
Guest User

322.Coin Change | Time: O (A*c) | Space: O(A)

a guest
Jul 23rd, 2019
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.95 KB | None | 0 0
  1. import java.util.Arrays;
  2.  
  3. /*
  4.     Leetcode problem: https://leetcode.com/problems/coin-change/ (Coin Change 1)
  5.     Solution from: https://www.youtube.com/watch?v=jgiZlGzXMBw
  6.     Github repo: https://github.com/bephrem1/backtobackswe/blob/master/Dynamic%20Programming%2C%20Recursion%2C%20%26%20Backtracking/changeMakingProblem.java
  7. */
  8.  
  9. public class CoinChange {
  10.    
  11.     public static int coinChangeBottomUp(int[] coins, int amount) {  
  12.         // We use this to fill the dp table with default values
  13.         int max = amount + 1;
  14.  
  15.         // This table will store the answer to our sub problems
  16.         int[] dp = new int[amount + 1];
  17.  
  18.         // Initialize the dp table
  19.         Arrays.fill(dp, max);
  20.  
  21.         /*
  22.             The answer to making change with minimum coins for 0
  23.             will always be 0 coins no matter what the coins we are
  24.             given are
  25.         */
  26.         dp[0] = 0;
  27.  
  28.         // Solve every subproblem from 1 to amount
  29.         for (int i = 1; i <= amount; i++) {
  30.             // For each coin we are given
  31.             for (int j = 0; j < coins.length; j++) {
  32.                 // If it is less than or equal to the sub problem amount
  33.                 if (coins[j] <= i) {
  34.                     // Try it. See if it gives us a more optimal solution
  35.                     dp[i] = Math.min(dp[i], dp[i - coins[j]] + 1);
  36.                 }
  37.             }
  38.         }
  39.  
  40.         /*
  41.             dp[amount] has our answer. If we do not have an answer then dp[amount]
  42.             will be amount + 1 and hence dp[amount] > amount will be true. We then
  43.             return -1.
  44.             Otherwise, dp[amount] holds the answer
  45.         */
  46.         return dp[amount] > amount ? -1 : dp[amount];
  47.  
  48.     }    
  49.  
  50.     public static void main(String arg[]) {
  51.         int [] coins1 = {1, 2, 5};
  52.         int amount1 = 11;
  53.         int result1 = coinChangeBottomUp(coins1, amount1);
  54.         System.out.println("Result is " + result1);
  55.  
  56.  
  57.     }
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement