Coin Change (Leetcode 322) - Coding Interview Question

Mani
Mani
Educating everyone with the beauty of programming!!

You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money.

Return the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.

You may assume that you have an infinite number of each kind of coin.

Example 1:

Input: coins = [1,2,5], amount = 11
Output: 3
Explanation: 11 = 5 + 5 + 1

Example 2:

Input: coins = [2], amount = 3
Output: -1

Example 3:

Input: coins = [1], amount = 0
Output: 0

Example 4:

Input: coins = [1], amount = 1
Output: 1

Example 5:

Input: coins = [1], amount = 2
Output: 2

Constraints:

  • 1 <= coins.length <= 12
  • 1 <= coins[i] <= 231 - 1
  • 0 <= amount <= 104

Solution:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import java.util.Arrays;

/**
 * This is a variation of Unbounded Knapsack DP.
 * Important points to note:
 * Initialization for dp[i][0] = 0 for all i.
 * If an element is not included it means its not included in any of the counts.
 * Note the subtle difference in code between 0/1 Knapsack vs Unbounded Knapsack.
 * Time Complexity: O(N ^ 2)
 * Space Complexit: O(N ^ 2)
 */
class Solution {
    public int coinChange(int[] w, int c) {
        int[][] dp = new int[w.length + 1][c + 1];
        for (int[] d : dp) {
            Arrays.fill(d, Integer.MAX_VALUE / 2);
        }
        dp[0][0] = 0;
        for (int i = 1; i <= w.length; i++) {
            dp[i][0] = 0;
        }
        for (int i = 1; i <= w.length; i++) {
            for (int j = 1; j <= c; j++) {
                if (w[i - 1] <= j) {
                    dp[i][j] = Math.min(1 + dp[i][j - w[i - 1]], dp[i - 1][j]);
                } else {
                    dp[i][j] = dp[i - 1][j];
                }
            }
        }

        return dp[w.length][c] == Integer.MAX_VALUE / 2 ? -1 : dp[w.length][c];
    }
}
Drop your comments below for any questions or comments. For full list of must learn top interview questions Click Here: Must Learn Top Interview Questions

Rating: