322. Coin Change
Previous318. Maximum Product of Word LengthsNext323. Number of Connected Components in an Undirected Graph
Last updated
Last updated
/**
* Time complexity : O(S*n). where S is the amount. On each step the
* algorithm finds the next F(i) in n iterations, where 1 < i <= S.
* Therefore in total the iterations are S*n.
* Space complexity : O(S). We use extra space for the memoization table.
*/
class Solution {
public int coinChange(int[] coins, int amount) {
if(amount == 0) {
return 0;
}
int[] dp = new int[amount+1];
for(int i = 1; i <= amount; i++) {
int min = Integer.MAX_VALUE;
for(int coin: coins) {
if(i-coin >= 0 && dp[i-coin] != Integer.MAX_VALUE) {
min = Math.min(min, dp[i-coin]+1);
}
}
dp[i] = min;
}
return dp[amount] == Integer.MAX_VALUE? -1: dp[amount];
}
}