LeetCode 0887. Super Egg Drop Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
0887. Super Egg Drop

Description

You are given k identical eggs and you have access to a building with n floors labeled from 1 to n.

You know that there exists a floor f where 0 <= f <= n such that any egg dropped at a floor higher than f will break, and any egg dropped at or below floor f will not break.

Each move, you may take an unbroken egg and drop it from any floor x (where 1 <= x <= n). If the egg breaks, you can no longer use it. However, if the egg does not break, you may reuse it in future moves.

Return the minimum number of moves that you need to determine with certainty what the value of f is.

 

Example 1:

Input: k = 1, n = 2
Output: 2
Explanation: 
Drop the egg from floor 1. If it breaks, we know that f = 0.
Otherwise, drop the egg from floor 2. If it breaks, we know that f = 1.
If it does not break, then we know f = 2.
Hence, we need at minimum 2 moves to determine with certainty what the value of f is.

Example 2:

Input: k = 2, n = 6
Output: 3

Example 3:

Input: k = 3, n = 14
Output: 4

 

Constraints:

  • 1 <= k <= 100
  • 1 <= n <= 104

Solutions

Solution 1

PythonJavaC++GoTypeScript
class Solution: def superEggDrop(self, k: int, n: int) -> int: @cache def dfs(i: int, j: int) -> int: if i < 1: return 0 if j == 1: return i l, r = 1, i while l < r: mid = (l + r + 1) >> 1 a = dfs(mid - 1, j - 1) b = dfs(i - mid, j) if a <= b: l = mid else: r = mid - 1 return max(dfs(l - 1, j - 1), dfs(i - l, j)) + 1 return dfs(n, k)(code-box)

Solution 2

PythonJavaC++GoTypeScript
class Solution: def superEggDrop(self, k: int, n: int) -> int: f = [[0] * (k + 1) for _ in range(n + 1)] for i in range(1, n + 1): f[i][1] = i for i in range(1, n + 1): for j in range(2, k + 1): l, r = 1, i while l < r: mid = (l + r + 1) >> 1 a, b = f[mid - 1][j - 1], f[i - mid][j] if a <= b: l = mid else: r = mid - 1 f[i][j] = max(f[l - 1][j - 1], f[i - l][j]) + 1 return f[n][k](code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !