Best starting layer for a falling ball with an energy budget
I was asked this
No reports yet. Sign in to say where you were asked it.
A ball falls through a tower of n layers, numbered 0 (top) to n - 1 (bottom). You get two integer arrays of length n and one integer:
-
costs[i](>= 0): the energy the ball spends to pass through layeri. -
points[i](may be negative): the score added when the ball passes through layeri. -
energy(>= 0): the energy the ball starts with.
You drop the ball at any layer s you choose. From there it must keep falling: it passes layer s, then s + 1, and so on, as long as its remaining energy is at least the cost of the next layer. It stops at the first layer it cannot afford, or after the bottom layer. Points do not give energy back.
Implement best_drop(costs: list[int], points: list[int], energy: int) -> tuple[int, int] that returns the best total score over all starting layers and the smallest starting layer that achieves it. If the ball can pass no layer from any start, the score is 0. For an empty tower return (0, 0).
Constraints: 0 <= n <= 10^5, 0 <= costs[i] <= 10^4, -10^4 <= points[i] <= 10^4, 0 <= energy <= 10^9. Aim for better than O(n^2).
Example 1
costs = [2, 3, 1, 4]
points = [5, -2, 4, 3]
energy = 6
Output: (7, 0). From layer 0 the ball passes layers 0, 1, 2 (cost 6) for 5 - 2 + 4 = 7. From layer 2 it passes layers 2 and 3 (cost 5) for 7 as well; layer 0 is the smaller start.
Example 2
costs = [1, 1, 1]
points = [-1, -1, -1]
energy = 1
Output: (-1, 0). Every start passes exactly one layer, and the ball cannot choose to stop.
Likely follow-up: the player may stop the ball after any layer. Return the best score in that case.
Reconstructed from the reported question; details may differ from what interviewers ask.
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.
Sign in to submit your code; every attempt is kept here.
