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

added matrix-chain-multiplication and egg-dropping puzzle -2 approaches #546

Closed
wants to merge 2 commits into from
Closed
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
41 changes: 41 additions & 0 deletions C++/dynamic programming/eggDropping.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
#include<bits/stdc++.h>
using namespace std;

// recursive solution
int eggDrop(int e, int f){
if(f==0 || f==1) return f;
if(e == 1) return f;

int res = INT_MAX;
for(int k=1; k<=f; k++){
int tempAns = 1 + max(eggDrop(e, f-k), eggDrop(e-1, k-1));
res = min(res, tempAns);
}

return res;
}

// memoization solution
int dp[100][100];
int eggDrop_M(int e, int f){
if(f==0 || f==1) return f;
if(e == 1) return f;

if(dp[e][f] != -1) return dp[e][f];

int res = INT_MAX;
for(int k=1; k<=f; k++){
int tempAns = 1 + max(eggDrop(e, f-k), eggDrop(e-1, k-1));
res = min(res, tempAns);
}

return dp[e][f] = res;
}

int main(){
int egg = 2, floor = 10;
memset(dp, -1, sizeof(dp));
cout<<eggDrop_M(egg, floor);

return 0;
}
41 changes: 41 additions & 0 deletions C++/dynamic programming/matrixChainMultiplication.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
#include<bits/stdc++.h>
using namespace std;

// recursive solution
int MCM(int *arr, int i, int j){
if(i >= j) return 0;

int res = INT_MAX;
for(int k=i; k<j; k++){
int tempAns = MCM(arr, i, k) + MCM(arr, k+1, j) + arr[i-1]*arr[k]*arr[j];
res = min(res, tempAns);
}

return res;
}

// memoization solution
int dp[100][100];
int MCM_M(int *arr, int i, int j){
if(i >= j) return 0;

if(dp[i][j] != -1) return dp[i][j];

int res = INT_MAX;
for(int k=i; k<j; k++){
int tempAns = MCM_M(arr, i, k) + MCM_M(arr, k+1, j) + arr[i-1]*arr[k]*arr[j];
res = min(res, tempAns);
}

return dp[i][j] = res;
}

int main(){
int arr[] = {10, 20, 30, 40, 30};
int n = sizeof(arr)/sizeof(int);
memset(dp, -1, sizeof(dp));

cout<<MCM_M(arr, 1, n-1);

return 0;
}