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

Prob-1 & 2 solutions added #35

Open
wants to merge 2 commits 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
35 changes: 35 additions & 0 deletions CoinChange.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/*
Author: Akhilesh Borgaonkar
Problem: LC 322. Coin Change (DP-1)
Approach: Using Dynamic Programming approach here to find the pattern of repeating sub-problems.
Time Complexity: O(m*n) where m is number of coins and n is amount
Space complexity: O(1) constant
LC verified
*/

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

for(int i=0; i<r; i++)
dp[i][0]=0;

for(int j=1; j<c; j++)
dp[0][j]=99999;

for(int i=1; i<r; i++){
for(int j=1; j<c; 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);
}
}
int result = dp[coins.length][amount];
if(result >= 99999)
return -1;
return result;
}
}
23 changes: 23 additions & 0 deletions HouseRobber.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
/*
Author: Akhilesh Borgaonkar
Problem: LC 198. House Robber (DP-1)
Approach: Using Dynamic programming approach to find the pattern of repeating sub-problems. Further optimized it by using just 2 variables to store
previous problem results.
Time Complexity: O(n) where n is number of elements in array.
Space complexity: O(1) constant.
LC Verified.
*/

class Solution {
public int rob(int[] nums) {
int chosen=0, notChosen=0;

for(int i=0; i<nums.length; i++){
int temp = chosen;
chosen = notChosen + nums[i];
notChosen = Math.max(temp, notChosen);
}

return Math.max(chosen, notChosen);
}
}