Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions CoinChange.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
public class CoinChange {

public static int coinChange(int[] coins, int amount) {
int n = coins.length;
int m = amount;
int [][] dp = new int [n+1][m+1];
for (int j = 1; j <=m; j++) {
dp[0][j] = amount +1;
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
if (coins[i-1] > j) {
dp[i][j] = dp[i-1][j];
} else {
dp[i][j] = Math.min(dp[i-1][j], 1 + dp[i][j-coins[i-1]]);
}
}}
int result = dp[n][m];
if(result>=amount+1){
return -1;
}
return result;


}

public static void main(String[] args) {
int[] coins = {1, 2, 5};
int amount = 11;
System.out.println(coinChange(coins, amount));
}

}
// Output: 3 (11 can be made with 5 + 5 + 1)
// Time Complexity: O(n*m) where n is the number of coins and m is the amount.
// Space Complexity: O(n*m) for the dp array.
26 changes: 26 additions & 0 deletions HouseRobber.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
public class HouseRobber {

public static int rob(int[] nums) {
int n = nums.length;
if (n == 0) return 0;
if (n == 1) return nums[0];
int[] dp = new int[n];

dp[0] = nums[0];
dp[1] = Math.max(nums[0], nums[1]);

for (int i = 2; i < n; i++) {
dp[i] = Math.max(dp[i - 1], nums[i] + dp[i - 2]);
}

return dp[n - 1];
}

public static void main(String[] args) {
int[] nums = {2, 7, 9, 3, 1};

System.out.println(rob(nums));
}
} // Output: 12 (rob house 1, 3, and 5)
//Time Complexity: O(n) where n is the number of houses.
//Space Complexity: O(n) for the dp array.