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
34 changes: 34 additions & 0 deletions CoinChange.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
// Time Complexity: O(mn)
// Space Complexity: O(mn)

// 1: We maintain a dp table where dp[i][j] contains the total coins we have used to make amount j using coins i so far available to us
// 2: We check to make sure that the denomination is greater than the amount, else we will only have case0
// 3: If not, we add case0 and case1 to have the total running sum through which we can return the last element of the dp table
class Solution {
public int coinChange(int[] coins, int amount) {
if(coins.length == 0 || coins == null) return -1;
int n = coins.length;
int m = amount;
int[][]dp = new int[n+1][m+1];
for(int i = 1;i<=m; i++){
dp[0][i] = amount+1;
}
for(int i = 1; i<=n;i++){
for(int j=1; j<=m; j++){
// when denomination > amount
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 res = dp[n][m];
if(res > amount){
return -1;
}
return res;
}
}
27 changes: 27 additions & 0 deletions HouseRobber.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
// Time Complexity : O(n)
// Space Complexity : O(1)
// Did this code successfully run on Leetcode : Yes
// Any problem you faced while coding this : No


// Your code here along with comments explaining your approach
// 1: We maintain variables to calculate the max amount the robber can make
// 2: We have prev and curr pointers that hold the max amount while iterating through the array
// 3: Once we have completed iteration, we return the curr amount which holds the total max value that the robber could make
class Solution {
public int rob(int[] nums) {
if(nums.length == 1) return nums[0];

int n = nums.length;
int prev = nums[0];
int curr = Math.max(nums[0], nums[1]);

for(int i = 2; i<n; i++){
int temp = curr;
curr = Math.max(curr, prev + nums[i]);
prev = temp;
}

return curr;
}
}