Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

DP-1 : Done #1727

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
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
32 changes: 32 additions & 0 deletions CoinChange.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import java.util.Arrays;

// Time Complexity :O(na) where nis no of coins and a is targetamount
// Space Complexity :O(a)
// Did this code successfully run on Leetcode :yes
// Any problem you faced while coding this :no

public class CoinChange {
public static int coinChange(int[] coins, int amount) {
// DP array to store minimum coins for each amount
int[] dp = new int[amount + 1];
Arrays.fill(dp, Integer.MAX_VALUE - 1); // Initialize with a large value
dp[0] = 0; // Base case: 0 coins needed for amount 0

// Process each coin
for (int coin : coins) {
for (int i = coin; i <= amount; i++) {
dp[i] = Math.min(dp[i], dp[i - coin] + 1);
}
}

// If dp[amount] is still a large value, return -1
return dp[amount] == Integer.MAX_VALUE - 1 ? -1 : dp[amount];
}

public static void main(String[] args) {
int[] coins = {1, 2, 5};
int amount = 10;
System.out.println("Fewest coins required: " + coinChange(coins, amount)); // Output: 3
}

}
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

public class HouseRobber {
public int rob(int[] nums) {
if (nums == null || nums.length == 0) return 0; // No houses
if (nums.length == 1) return nums[0]; // Only one house

// Variables to store the maximum profit up to the previous two houses
int prev1 = 0; // Max profit up to the previous house
int prev2 = 0; // Max profit up to the house before the previous

for (int num : nums) {
int temp = prev1;
// Max profit for the current house is the max of:
// 1. Robbing this house + profit up to two houses before
// 2. Not robbing this house (carry forward the previous max profit)
prev1 = Math.max(prev1, prev2 + num);
prev2 = temp;
}

return prev1; // Maximum profit
}

}