← Questions

Best starting layer for a falling ball with an energy budget

0
GoogleCoding

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 layer i.
  • points[i] (may be negative): the score added when the ball passes through layer i.
  • 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.

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding