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
59 changes: 59 additions & 0 deletions coin_change.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
class Solution {
public:
int coinChange(vector<int>& coins, int amount) {
//TC: O(m*n)
//SC: O(m*n)
vector<vector<int>> dp(coins.size()+1,vector<int>(amount+1));
if(coins.size()==0)
return -1;

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

for(int i=1;i<dp.size();i++)
{
for(int j=1; j<dp[0].size();j++)
{
if(j<coins[i-1])
{
dp[i][j]=dp[i-1][j];
}
else
{
dp[i][j]=min(dp[i-1][j], dp[i][j-coins[i-1]]+1);
}
}
}
if(dp[coins.size()][amount]==amount+1)
return -1;
return dp[coins.size()][amount];



//exhaustive method:
/* return recurse(coins, 0, amount, 0);
}

int recurse(vector<int>& coins, int index, int amount, int coinsUsed)
{
if(index==coins.size()|| amount<0) return -1;
if(amount==0) return coinsUsed;

int case2= recurse(coins, index, amount-coins[index], coinsUsed+1);
int case1=recurse(coins, index+1, amount, coinsUsed);


if(case1==-1) return case2;
if(case2==-1) return case1;
return min(case1, case2);
}*/


}
};


56 changes: 56 additions & 0 deletions house_robber.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
class Solution {
public:
int rob(vector<int>& nums) {
//Appraoch 1 - go exhaustive- all possible value evaluation

// TC: 2^n
// SC: O(n)
// return helper(nums, 0, 0);
// }
// int helper(vector<int>& nums, int index, int earned)
// {
// if(index >= nums.size())
// {
// return earned;
// }
// //not choose
// int case1=helper(nums, index+1, earned);
// //choose
// int case2=helper(nums, index+2, earned+nums[index]);

// return max(case1, case2);
// }

//Approach 2: *******2D array***** dp where we store values of robbings and values when not robbed. if we choose to not rob the current house then the value should come from earlier robbings!! if chose to rob the current house then current house robbing value must be added to the earlier non-robbed value because only alternate hosues can be robbed. in the end we get maximum between both the approaches

// TC: O(n)
// SC: O(n)

// int n=nums.size();
// vector<vector<int>> dp(n,vector<int>(2));
// dp[0][0]=0;
// dp[0][1]=nums[0];
// for(int i=1;i<n;i++)
// {
// dp[i][0]=max(dp[i-1][1], dp[i-1][0]);
// dp[i][1]=dp[i-1][0]+nums[i];
// }
// return max(dp[n-1][0], dp[n-1][1]);


//Approach 3: DP with only 2 variables
// TC: O(n)
// SC: O(1)
int n=nums.size();
int skip=0, take=nums[0];
for(int i=1;i<n;i++)
{
int temp=skip;
skip=max(skip, take);
take=temp+nums[i];

}
return max(skip, take);

}
};