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
38 changes: 38 additions & 0 deletions CoinChange.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
// Time Complexity : O(n × amount)
// Space Complexity : O(n × amount)
// Did this code successfully run on Leetcode : Yes

// - Build a DP table where dp[i][j] = minimum coins needed to make amount j using first i coin types.
// - For each coin, either skip it: dp[i-1][j], or take it: dp[i][j-coin] + 1.
// - Take the minimum of both choices; if final value is amount + 1, return -1.



class Solution {
public int coinChange(int[] coins, int amount) {
int[][] dp = new int[coins.length + 1][amount + 1];

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

for(int i = 1; i < coins.length + 1; i++) {
for(int j = 1; j < amount + 1; j++) {
if(coins[i - 1] > j) {
dp[i][j] = dp[i -1][j];
continue;
}

dp[i][j] = Math.min(
dp[i -1][j],
dp[i][j - coins[i - 1]] + 1
);
}
}

if(dp[coins.length][amount] == amount + 1) {
return -1;
}
return dp[coins.length][amount];
}
}
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(n)
// Did this code successfully run on Leetcode : Yes

// - dp[i] stores the maximum money we can rob from houses 0...i.
// - At each house, either skip it: dp[i-1], or rob it: nums[i] + dp[i-2].
// - Take the maximum of these two choices: dp[i] = max(dp[i-1], nums[i] + dp[i-2])


class Solution {
public int rob(int[] nums) {
if(nums.length == 1) {
return nums[0];
}
int[] dp = new int[nums.length];
dp[0] = nums[0];
dp[1] = Math.max(nums[0], nums[1]);
for(int i = 2; i < nums.length; i++) {
dp[i] = Math.max(
dp[i - 1],
nums[i] + dp[i - 2]
);
}

return dp[nums.length - 1];
}
}