Skip to content

Commit 7cca3aa

Browse files
committed
Refactor EggDropping.java to improve readability and performance
1 parent 9fbd9f1 commit 7cca3aa

File tree

1 file changed

+11
-12
lines changed

1 file changed

+11
-12
lines changed

src/main/java/com/thealgorithms/dynamicprogramming/EggDropping.java

Lines changed: 11 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,14 @@
66
* floor from which if an egg is dropped, it will break.
77
* Time Complexity: O(n * m * m), where n is number of eggs and m is number of floors
88
* Space Complexity: O(n * m) to store the DP table
9+
* co-author @manishraj27
910
*/
1011
public final class EggDropping {
11-
12+
1213
private EggDropping() {
1314
// private constructor to prevent instantiation
1415
}
15-
16+
1617
/**
1718
* Finds minimum number of trials needed in worst case for n eggs and m floors
1819
*
@@ -28,19 +29,19 @@ public static int minTrials(int eggs, int floors) {
2829

2930
// dp[i][j] represents minimum number of trials needed for i eggs and j floors
3031
int[][] dp = new int[eggs + 1][floors + 1];
31-
32+
3233
// Base case 1: Zero trials for zero floor
3334
// Base case 2: One trial for one floor
3435
for (int i = 1; i <= eggs; i++) {
3536
dp[i][0] = 0;
3637
dp[i][1] = 1;
3738
}
38-
39+
3940
// Base case 3: With one egg, need to try every floor from bottom
4041
for (int j = 1; j <= floors; j++) {
4142
dp[1][j] = j;
4243
}
43-
44+
4445
// Fill rest of the entries in table using optimal substructure property
4546
for (int i = 2; i <= eggs; i++) {
4647
for (int j = 2; j <= floors; j++) {
@@ -55,22 +56,20 @@ public static int minTrials(int eggs, int floors) {
5556
}
5657
}
5758
}
58-
59+
5960
return dp[eggs][floors];
6061
}
61-
62+
6263
/**
6364
* Example usage
6465
*/
6566
public static void main(String[] args) {
6667
try {
6768
// 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+
7171
// 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));
7473
} catch (IllegalArgumentException e) {
7574
System.err.println("Error: " + e.getMessage());
7675
}

0 commit comments

Comments
 (0)