6
6
* floor from which if an egg is dropped, it will break.
7
7
* Time Complexity: O(n * m * m), where n is number of eggs and m is number of floors
8
8
* Space Complexity: O(n * m) to store the DP table
9
+ * co-author @manishraj27
9
10
*/
10
11
public final class EggDropping {
11
-
12
+
12
13
private EggDropping () {
13
14
// private constructor to prevent instantiation
14
15
}
15
-
16
+
16
17
/**
17
18
* Finds minimum number of trials needed in worst case for n eggs and m floors
18
19
*
@@ -28,19 +29,19 @@ public static int minTrials(int eggs, int floors) {
28
29
29
30
// dp[i][j] represents minimum number of trials needed for i eggs and j floors
30
31
int [][] dp = new int [eggs + 1 ][floors + 1 ];
31
-
32
+
32
33
// Base case 1: Zero trials for zero floor
33
34
// Base case 2: One trial for one floor
34
35
for (int i = 1 ; i <= eggs ; i ++) {
35
36
dp [i ][0 ] = 0 ;
36
37
dp [i ][1 ] = 1 ;
37
38
}
38
-
39
+
39
40
// Base case 3: With one egg, need to try every floor from bottom
40
41
for (int j = 1 ; j <= floors ; j ++) {
41
42
dp [1 ][j ] = j ;
42
43
}
43
-
44
+
44
45
// Fill rest of the entries in table using optimal substructure property
45
46
for (int i = 2 ; i <= eggs ; i ++) {
46
47
for (int j = 2 ; j <= floors ; j ++) {
@@ -55,22 +56,20 @@ public static int minTrials(int eggs, int floors) {
55
56
}
56
57
}
57
58
}
58
-
59
+
59
60
return dp [eggs ][floors ];
60
61
}
61
-
62
+
62
63
/**
63
64
* Example usage
64
65
*/
65
66
public static void main (String [] args ) {
66
67
try {
67
68
// Example: 2 eggs and 4 floors
68
- System .out .println ("Minimum number of trials in worst case with 2 eggs and 4 floors: "
69
- + minTrials (2 , 4 ));
70
-
69
+ System .out .println ("Minimum number of trials in worst case with 2 eggs and 4 floors: " + minTrials (2 , 4 ));
70
+
71
71
// Additional test case
72
- System .out .println ("Minimum number of trials in worst case with 3 eggs and 5 floors: "
73
- + minTrials (3 , 5 ));
72
+ System .out .println ("Minimum number of trials in worst case with 3 eggs and 5 floors: " + minTrials (3 , 5 ));
74
73
} catch (IllegalArgumentException e ) {
75
74
System .err .println ("Error: " + e .getMessage ());
76
75
}
0 commit comments