forked from super30admin/DP-1
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Completed problems super30admin#21 & super30admin#22
- Loading branch information
1 parent
fb24b51
commit 1948e44
Showing
2 changed files
with
51 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
|
||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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]; | ||
} | ||
} |