File tree Expand file tree Collapse file tree 1 file changed +41
-0
lines changed
CPP/algorithms/dynamic_programming Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change 1+ #include < iostream>
2+ #include < vector>
3+ #include < climits>
4+ using namespace std ;
5+
6+ // Function to find minimum number of attempts needed
7+ int eggDrop (int eggs, int floors) {
8+ vector<vector<int >> dp (eggs + 1 , vector<int >(floors + 1 , 0 ));
9+
10+ // Base cases
11+ for (int i = 1 ; i <= eggs; i++)
12+ dp[i][0 ] = 0 , dp[i][1 ] = 1 ;
13+ for (int j = 1 ; j <= floors; j++)
14+ dp[1 ][j] = j;
15+
16+ // Fill the rest using DP
17+ for (int e = 2 ; e <= eggs; e++) {
18+ for (int f = 2 ; f <= floors; f++) {
19+ dp[e][f] = INT_MAX;
20+ for (int k = 1 ; k <= f; k++) {
21+ int attempts = 1 + max (dp[e - 1 ][k - 1 ], dp[e][f - k]);
22+ dp[e][f] = min (dp[e][f], attempts);
23+ }
24+ }
25+ }
26+
27+ return dp[eggs][floors];
28+ }
29+
30+ int main () {
31+ int eggs, floors;
32+ cout << " Enter number of eggs: " ;
33+ cin >> eggs;
34+ cout << " Enter number of floors: " ;
35+ cin >> floors;
36+
37+ int minAttempts = eggDrop (eggs, floors);
38+ cout << " Minimum number of attempts needed: " << minAttempts << endl;
39+
40+ return 0 ;
41+ }
You can’t perform that action at this time.
0 commit comments