Algorithm


Problem Name: 887. Super Egg Drop

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
 

Code Examples

#1 Code Example with Javascript Programming

Code - Javascript Programming


const superEggDrop = function(K, N) {
  let lo = 1,
    hi = N,
    mi
  while (lo < hi) {
    mi = ((lo + hi) / 2) >> 0
    if (f(mi, K, N)  <  N) lo = mi + 1
    else hi = mi
  }
  return lo
}

function f(x, K, N) {
  let ans = 0,
    r = 1,
    i = 1
  for (let i = 1; i <= K; ++i) {
    r = ((r * (x - i + 1)) / i) >> 0
    ans += r
    if (ans >= N) break
  }
  return ans
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
k = 1, n = 2

Output

x
+
cmd
2

#2 Code Example with Python Programming

Code - Python Programming


class Solution:
    def superEggDrop(self, K, N):
        drops = 0                           # the number of eggs dropped
        floors = [0 for _ in range(K + 1)]  # floors[i] is the number of floors that can be checked with i eggs

        while floors[K] < N:                # until we can reach N floors with K eggs 

            for eggs in range(K, 0, -1):
                floors[eggs] += 1 + floors[eggs - 1]
            drops += 1

        return drops
Copy The Code & Try With Live Editor

Input

x
+
cmd
k = 1, n = 2

Output

x
+
cmd
2

#3 Code Example with C# Programming

Code - C# Programming

start coding...
Copy The Code & Try With Live Editor
Advertisements

Demonstration


Previous
#886 Leetcode Possible Bipartition Solution in C, C++, Java, JavaScript, Python, C# Leetcode
Next
#888 Leetcode Fair Candy Swap Solution in C, C++, Java, JavaScript, Python, C# Leetcode