Although binary search can solve this problem, there is an O(1) solution if you think about this mathematically.

*If he uses staircase, he takes f amount of time to reach floor f from floor f-1.*

Thus, to reach floor number f total time taken is 1+2+3+...+f = \frac{f(f+1)}{2}.

*Elevator takes 1 unit time to go from any floor to it’s neighbouring floors.*

Thus, time taken by the elevator to reach a certain floor while descending is N-f.

Now, from the problem it is clear that catching the elevator on its way down and then riding it to the top is the quicker than climbing to the top. However waiting too long at some floor x is also not a good idea if it is possible to reach floor x+1 by the time the elevator reaches floor x+1, as it wastes 2 units of time. So our aim is to climb the stairs to the maximum floor possible without missing the elevator. Which amounts to finding the largest x for which

\frac{x(x+1)}{2} \le N-x

This is a quadratic inequality, solving which we get the maximum integer value of x as

x = \bigg\lfloor\frac{-3 + \sqrt{9+8N}}{2}\bigg\rfloor

The total time taken is the time taken for the elevator to come to this floor x and go up again, which is 2(N-x).

A corner case arises when N=1, as *not* taking the elevator is quicker than taking it. Just climbing one floor is 1 unit whereas waiting for the elevator would take 2 units of time.

Solution in Python: here