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
41 changes: 41 additions & 0 deletions CoinChange.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
// Approach - Recursion can be used to pursue exhaustive path, but since this problem has repeated sub problems
// we could use Dynamic programming.
//Time Complexity - O(mxn)
//Space Complexity - O(mxn)

class CoinChange {
public int coinChange(int[] coins, int amount) {

//Validate the inputs
if(coins == null || coins.length == 0){
return 0;
}

int m = coins.length;
int n = amount;

int[][] dp = new int[m+1][n+1];

// Fill first row coins[0][j] with any amount higher than the given amount
for (int j = 1; j <= n; j++){
dp[0][j] = amount + 1;
}

for(int i = 1; i <= m; i++)
{
for(int j = 1; j <= n; j++)
{
// If we don't have the availability of choose case when amount is less than the denomination, copy the above case
if (j < coins[i-1]){
dp[i][j] = dp[i-1][j];
}
else
{
dp[i][j] = Math.min(dp[i-1][j], dp[i][j-coins[i-1]]+1);
}
}
}
if(dp[m][n] == amount+1) return -1;
return dp[m][n];
}
}
28 changes: 28 additions & 0 deletions HouseRobber.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
// Approach - Recursion can be used to pursue exhaustive path, but since this problem has repeated sub problems
// we could use Dynamic programming.
//Time Complexity: O(n)
//Space Complexity: O(n)

class HouseRobber {
public int rob(int[] nums) {

if (nums.length == 0){
return 0;
}

if (nums.length == 1) return nums[0];

int n = nums.length;
int [] dp = new int[n];

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

//Maximum between choose case vs non choose case where we cannot select the immediate neighbouring house.
for(int i=2 ; i <n; i++){
dp[i] = Math.max(dp[i-1], nums[i] + dp[i-2]);
}

return dp[n-1];
}
}