Miscellaneous Talk: The Egg Falling Problem of Classic Algorithm

0 Preface

The egg falling problem can be regarded as a classic algorithmic problem. Leetcode is also included on it. It is one of the few problems I have collected. It is indeed a very interesting problem. Teacher Li Yongle also made a video to talk about this problem.

It just happened that today I was not feeling well, I had a bad cold, and I didn't have much energy to learn some new things, so I just picked up the old things and reviewed them a little bit.

1. Introduction

First, let's take a look at the description of the classic algorithm problem:

  • You have K eggs in your hand, and then there is an N-storey building with a critical floor F. When an egg falls from the F floor or a lower floor, it will not break; on the contrary, it will be an egg When falling from the upper floor higher than the F floor, the egg will break. It takes at least a few experiments to ensure that the critical layer F is found.

The title of the corresponding leetcode is described as:

2. Algorithm ideas

In fact, the first reaction I got on this topic was whether it was possible to directly give the optimal solution. The result was better. Later, after reading some solutions, I found that this is a classic problem of dynamic programming, so at least the algorithm is Can be solved.

Obviously, if there is only one egg, then there are several floors and several experiments must be done to ensure that the critical layer F can be found; and if there is only one floor, then no matter how many eggs are on hand, the number of experiments required is once.

Then, we can quickly give the recurrence formula as follows:

dp[k][n] = min(1+max(dp[k-1][i-1], dp[k][n-i]) for i in range(1, n+1))

That is to say, to investigate the situation of each operation falling from the i-th floor, if it is not broken, then only the nith floor upstairs needs to be inspected; on the contrary, if it is broken, then only the k-1 eggs in the In this case, how many experiments are needed for i-1 floors to ensure that the critical floor is obtained.

3. Code implementation

Given the python code implementation is as follows:

class Solution:
    def superEggDrop(self, K: int, N: int) -> int:
        dp = [[0 for i in range(N+1)] for _ in range(K+1)]
        for k in range(1, K+1):
            for n in range(1, N+1):
                if k == 1:
                    dp[k][n] = n
                elif n == 1:
                    dp[k][n] = 1
                else:
                    dp[k][n] = min(1+max(dp[k-1][i-1], dp[k][n-i]) for i in range(1, n+1))
        return dp[K][N]

After submitting the code, I tested several examples and they were all correct. However, a timeout error occurred during code evaluation in LeetCode. After all, the time complexity of the above code is O (N 3) O(N^3)O ( N3 ) Theorder of magnitude.

4. Algorithm optimization

Another more elegant code implementation is given in leetcode.

First of all, his idea is not to explicitly calculate the specific answer for each clear K and N situation, as we gave earlier, but to solve the problem that when there are K eggs, do n experiments, at most You can be sure to determine how many floors are below the threshold floor .

We can also give the recurrence formula as follows:

dp[k][n] = dp[k-1][n-1] + 1 + dp[k][n-1]

Among them, k is consistent with the previous definition, which means that there are k eggs, and n means that there are at most n operations, which dp[k][n]means that when there are k eggs, how many floors below the threshold floor can be guaranteed after n operations.

5. Code Implementation

The python code is given as follows:

class Solution:
    def superEggDrop(self, K: int, N: int) -> int:
        dp = [[0 for _ in range(N+1)] for _ in range(K+1)]

        for n in range(1, N+1):
            for k in range(1, K+1):
                if k == 1:
                    dp[k][n] = n
                else:
                    dp[k][n] = dp[k-1][n-1] + 1 + dp[k][n-1]
                if dp[k][n] >= N:
                    return n
        return -1

Code complexity from the previous O (N 3) O(N^3)O ( N3 )Degenerate toO (N 2) O(N^2)O ( N2 ), After submitting the code, it is passed smoothly in the leetcode.

6. Summary

In summary, we have basically explained this question. However, the current execution efficiency is still not optimal. There are some improved solutions on LeetCode that will take time and can be further optimized, but the idea is the same, and the overall algorithm complexity is also O (N 2) O(N^ 2)O ( N2 ), but the details of the implementation are not the same. In order to better explain, we still use the above writing method, which is more explanatory.

If readers are interested in more efficient code, you can go to LeetCode to take a look.

Guess you like

Origin blog.csdn.net/codename_cys/article/details/111085961