Advertisement
exmkg

CoinChange

Feb 11th, 2025
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.96 KB | None | 0 0
  1. import java.util.Arrays;
  2. import java.util.Scanner;
  3.  
  4. public class CoinChange {
  5.  
  6.     public static void main(String[] args) {
  7.         Scanner scanner = new Scanner(System.in);
  8.  
  9.         // Read input: n (number of coins), x (target sum)
  10.         int n = scanner.nextInt();
  11.         int x = scanner.nextInt();
  12.  
  13.         // Read coin values into an array
  14.         int[] coins = new int[n];
  15.         for (int i = 0; i < n; i++) {
  16.             coins[i] = scanner.nextInt();
  17.         }
  18.  
  19.         // dp[i] stores the minimum number of coins needed to make sum 'i'
  20.         // Initialize dp array with a large value (x + 1) representing infinity.
  21.         // We use x + 1 because the maximum number of coins needed can't exceed x
  22.         // (if we only used coins of value 1).  Any value larger than x is effectively infinity.
  23.         int[] dp = new int[x + 1];
  24.         Arrays.fill(dp, x + 1);
  25.  
  26.         // Base case: 0 coins are needed to make a sum of 0
  27.         dp[0] = 0;
  28.  
  29.         // Iterate through all possible sums from 1 to x
  30.         for (int i = 1; i <= x; i++) {
  31.             // Iterate through each coin
  32.             for (int coin : coins) {
  33.                 // If the current coin's value is less than or equal to the current sum 'i'
  34.                 if (coin <= i) {
  35.                     // Check if using the current coin leads to a smaller number of coins
  36.                     // dp[i - coin] represents the minimum coins needed to make the sum (i - coin)
  37.                     // We add 1 to represent using the current coin.
  38.                     // We take the minimum between the current dp[i] and the new value.
  39.                     dp[i] = Math.min(dp[i], dp[i - coin] + 1);
  40.                 }
  41.             }
  42.         }
  43.  
  44.         // If dp[x] is still x + 1, it means no combination of coins could make the sum x
  45.         // Otherwise, dp[x] contains the minimum number of coins needed.
  46.         System.out.println(dp[x] > x ? -1 : dp[x]);
  47.  
  48.         scanner.close();
  49.     }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement