Skip to content

Commit

Permalink
Completed DP -1
Browse files Browse the repository at this point in the history
Completed problems super30admin#21 & super30admin#22
  • Loading branch information
rukhsard42 committed Sep 8, 2023
1 parent fb24b51 commit 1948e44
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
28 changes: 28 additions & 0 deletions Problem1.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
// Time Complexity : O(nXm) we loop through all numbers in nums and amount
// Space Complexity : O(nXm) size of dp array.
// Did this code successfully run on Leetcode : Yes
// Any problem you faced while coding this : No

public class Problem1 {

public int coinChange(int[] coins, int amount) {
if(coins.length == 0 || coins == null) return -1;

int[][] dp = new int[coins.length+1][amount+1];
for(int i = 0; i <= amount; i++){
dp[0][i] = amount+1;
}

for(int i = 1; i < coins.length+1; i++){
for(int j = 1; j < amount+1; j++){
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);
}
}
}
return dp[coins.length][amount] < amount + 1 ? dp[coins.length][amount] : -1;

}
}
23 changes: 23 additions & 0 deletions Problem2.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
// Time Complexity : O(n) we loop through all numbers in nums
// Space Complexity : O(n) size of dp array.
// Did this code successfully run on Leetcode : Yes
// Any problem you faced while coding this : No

public class Problem2 {
public int rob(int[] nums) {
if(nums == null || nums.length == 0) return 0;

int length = nums.length;
int[] dp = new int[length + 1];

//base case
dp[length] = 0;
dp[length - 1] = nums[nums.length - 1];

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

return dp[0];
}
}

0 comments on commit 1948e44

Please sign in to comment.