LeetCode in Kotlin

1884. Egg Drop With 2 Eggs and N Floors

Medium

You are given two 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.

In 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: n = 2

Output: 2

Explanation: We can drop the first egg from floor 1 and the second egg from floor 2.

If the first egg breaks, we know that f = 0.

If the second egg breaks but the first egg didn’t, we know that f = 1.

Otherwise, if both eggs survive, we know that f = 2.

Example 2:

Input: n = 100

Output: 14

Explanation: One optimal strategy is:

Constraints:

Solution

class Solution {
    fun twoEggDrop(n: Int): Int {
        // given x steps, the maximum floors I can test with two eggs
        val dp = IntArray(n + 1)
        for (i in 1..n) {
            // move is i, previous move is i - 1,
            // we put egg on floor i, if egg breaks, we can check i - 1 floors with i - 1 moves
            // if egg does not break, we can check dp[i-1] floors having two eggs to with i - 1
            // moves
            dp[i] = 1 + i - 1 + dp[i - 1]
            if (dp[i] >= n) {
                return i
            }
        }
        return 0
    }
}